在Ruby中,将2D数组值转换为散列数组的最有效方法是什么?其中键是从单独的数组中获取的?
例如,来自:
keys = ['First name', 'Last name', 'Phone number']
values = [['John', 'Smith', '555-1234'], ['Peter', 'Jones', '555-5678']]
要:
[
{'First name' => 'John',
'Last name' => 'Smith',
'Phone number' => '555-1234'},
{'First name' => 'Peter',
'Last name' => 'Jones',
'Phone number' => '555-5678'}
]
答案 0 :(得分:3)
你可以做到
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"}]