给你两个数组:
countries= [['Canada', 2], ['Chile', 1], ['China', 1]]
keys = [:country, :count]
你可以写
[keys].product(countries).map { |arr| arr.transpose.to_h }
#=> [{:country=>"Canada", :count=>2},
# {:country=>"Chile", :count=>1},
# {:country=>"China", :count=>1}]
或者干脆
countries.map { |country, cnt| { country: country, count: cnt } }
#=> [{:country=>"Canada", :count=>2},
# {:country=>"Chile", :count=>1},
# {:country=>"China", :count=>1}]
但第一个优点是无需更改键名更改代码。countries
事实上,如果数组和keys
两者都发生了变化,则无需更改代码,countries[i].size == keys.size
为 all提供i = 0..countries.size-1
。(见最后的例子。)
第一次计算的初始步骤如下。
a = [keys].product(countries)
#=> [[[:country, :count], ["Canada", 2]],
# [[:country, :count], ["Chile", 1]],
# [[:country, :count], ["China", 1]]]
请参阅Array#product。我们现在有
a.map { |arr| arr.transpose.to_h }
map
将 的第一个元素传递a
给块并将块变量arr
设置为该值:
arr = a.first
#=> [[:country, :count], ["Canada", 2]]
然后执行块计算:
b = arr.transpose
#=> [[:country, "Canada"], [:count, 2]]
b.to_h
#=> {:country=>"Canada", :count=>2}
所以我们看到a[0]
( arr
) 被映射到{:country=>"Canada", :count=>2}
。然后将接下来的两个元素a
传递给块并进行类似的计算,然后map
返回所需的三个哈希数组。请参阅Array#transpose和Array#to_h。
这是使用相同代码的第二个示例。
countries= [['Canada', 2, 9.09], ['Chile', 1, 0.74],
['China', 1, 9.33], ['France', 1, 0.55]]
keys = [:country, :count, :area]
[keys].product(countries).map { |arr| arr.transpose.to_h }
#=> [{:country=>"Canada", :count=>2, :area=>9.09},
# {:country=>"Chile", :count=>1, :area=>0.74},
# {:country=>"China", :count=>1, :area=>9.33},
# {:country=>"France", :count=>1, :area=>0.55}]