Rajagopalan
Rajagopalan

Reputation: 6064

how to convert this array into Hash

I have an array something like this

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

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. 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' => ['[email protected]', '[email protected]', '[email protected]']
}

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?

Upvotes: 0

Views: 128

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110665

arr = ['project','AAA','Division','BBB','TestingType','CCC',
       'Email','[email protected]','[email protected]','[email protected]']

idx = arr.index('Email')
  #=> 6 
Hash[*arr[0,idx], 'Email', arr[idx+1..-1]]
  #=> {"project"=>"AAA", "Division"=>"BBB", "TestingType"=>"CCC",
  #    "Email"=>["[email protected]", "[email protected]", "[email protected]"]} 

Upvotes: 1

iGian
iGian

Reputation: 11183

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"=>["[email protected]", "[email protected]", "[email protected]"]}

Upvotes: 1

Ilya
Ilya

Reputation: 13477

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"=>["[email protected]", "[email protected]", "[email protected]"]}

Upvotes: 5

Related Questions