简体   繁体   English

如何将此数组转换为哈希

[英]how to convert this array into Hash

I have an array something like this 我有一个像这样的数组

['project','AAA','Division','BBB','TestingType','CCC','Email','abc@gmail.com','def'@gmail.com','efg@gmail.com',...]

the email count varies. 电子邮件数量各不相同。 and also something may enter inside like 'project','AAA','Time','2323','Division','BBB','TestingType','CCC' Now you might have noticed that Time and 2323 entered so result hash must consist of 'Time'=>'2323' as well. 并且还可能在其中输入诸如'project','AAA','Time','2323','Division','BBB','TestingType','CCC'现在您可能已经注意到输入了时间和2323,所以结果哈希也必须由'Time'=>'2323'组成。 But Email anyway would be at the end. 但是无论如何,电子邮件将在最后。

I want to convert this array into a hash like this 我想将此数组转换为这样的哈希

resultHash = {
  'project' => 'AAA',
  'Division' => 'BBB',
  'TestingType' => 'CCC',
  'Email' => ['abc@gmail.com', 'def@gmail.com', 'efg@gmail.com']
}

The difficulty here for me is, email count varies every time. 对我而言,这里的困难在于,电子邮件计数每次都不同。 Can someone help to convert this array into a desired hash as given above? 有人可以如上所述将这个数组转换为所需的哈希吗?

It seems like you are looking for something like: 似乎您正在寻找类似的东西:

attributes, emails = *array.slice_before('Email')
Hash[*attributes].update(emails.first => emails[1..-1])
#=> {"project"=>"AAA", "Division"=>"BBB", "TestingType"=>"CCC", 
#    "Email"=>["abc@gmail.com", "def@gmail.com", "efg@gmail.com"]}

Just for having another option: 只是为了有另一个选择:

ary[ary.index('Email')..].partition{ |e| e == 'Email'}
.then { |k, v| ary[0..ary.index('Email')-1].each_slice(2).to_a << [k.first, v] }.to_h

#=> {"project"=>"AAA", "Division"=>"BBB", "TestingType"=>"CCC", "Email"=>["abc@gmail.com", "def@gmail.com", "efg@gmail.com"]}
arr = ['project','AAA','Division','BBB','TestingType','CCC',
       'Email','abc@gmail.com','def@gmail.com','efg@gmail.com']

idx = arr.index('Email')
  #=> 6 
Hash[*arr[0,idx], 'Email', arr[idx+1..-1]]
  #=> {"project"=>"AAA", "Division"=>"BBB", "TestingType"=>"CCC",
  #    "Email"=>["abc@gmail.com", "def@gmail.com", "efg@gmail.com"]} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM