我有两个数组。
product_name = ["Pomegranate", "Raspberry", "Miracle fruit", "Raspberry"]
product_quantity = [2, 4, 5, 5]我想知道如何初始化散列,使其成为
product_hash = {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}发布于 2017-03-19 08:18:43
发布于 2017-03-19 08:33:36
使用each_with_object:
product_name.zip(product_quantity)
.each_with_object({}) {|(k, v), h| h[k] ? h[k] += v : h[k] = v }
#=> {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}或者只使用带有默认值的散列:
product_name.zip(product_quantity)
.each_with_object(Hash.new(0)) {|(k, v), h| h[k] += v }
#=> {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}发布于 2017-03-19 13:49:36
这只是@llya的解决方案#2的一个细微的变化。
product_name.each_index.with_object(Hash.new(0)) { |i,h|
h[product_name[i]] += h[product_quantity[i]] } .https://stackoverflow.com/questions/42884331
复制相似问题