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'}
]
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"}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.