1

In Ruby, what's most efficient way of converting a 2D array of values to an array of hashes, where the keys are taken from a separate array?

For example, from:

keys = ['First name', 'Last name', 'Phone number']
values = [['John', 'Smith', '555-1234'], ['Peter', 'Jones', '555-5678']]

To:

[
  {'First name' => 'John',
   'Last name' => 'Smith',
   'Phone number' => '555-1234'},
  {'First name' => 'Peter',
   'Last name' => 'Jones',
   'Phone number' => '555-5678'}
]

1 Answer 1

3

You can do

array_of_hashs = values.map do |ary|
   keys.zip(ary).to_h
end

array_of_hashs
# => [{"First name"=>"John", "Last name"=>"Smith", "Phone number"=>"555-1234"}, 
# {"First name"=>"Peter", "Last name"=>"Jones", "Phone number"=>"555-5678"}] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! In Ruby 2.0 I had to change keys.zip(ary).to_h to Hash[keys.zip(ary)].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.