Ruby 2D数组到具有来自不同数组的键的哈希数组

时间:2014-07-07 10:16:15

标签: ruby arrays

在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'}
]

1 个答案:

答案 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"}]