鉴于我有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}
]
答案 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}
# => ]