如何在Ruby中生成3个数组的哈希值?

时间:2014-06-20 09:18:02

标签: ruby arrays hashmap

鉴于我有3个相互映射的数组。

fruit = ['apple', 'avocado', 'banana']
color = ['red', 'purple', 'yellow']
price = [30, 20, 50]

如何使用以下值创建哈希数组

[
 {fruit: 'apple', color: 'red', price: 30},
 {fruit: 'avocado', color: 'purple', price: 20},
 {fruit: 'banana', color: 'yellow', price: 50}
]

1 个答案:

答案 0 :(得分:4)

您可以使用zip交错数组,然后将它们映射到哈希数组中:

fruit.zip(color, price).map { |f, c, p| { fruit: f, color: c, price: p } }
# => [{:fruit=>"apple", :color=>"red", :price=>30}, 
# =>  {:fruit=>"avocado", :color=>"purple", :price=>20}, 
# =>  {:fruit=>"banana", :color=>"yellow", :price=>50}
# => ]