RUBY:将具有重复值的2个不同数组组合成哈希值

时间:2017-03-19 08:11:03

标签: arrays ruby hash

我有2个阵列。

product_name = ["Pomegranate", "Raspberry", "Miracle fruit", "Raspberry"]
product_quantity =  [2, 4, 5, 5]

我想知道如何初始化哈希,使其成为

product_hash = {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}

4 个答案:

答案 0 :(得分:4)

使用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}

答案 1 :(得分:1)

我会从这样的事情开始:

product_name.zip(product_quantity)
            .group_by(&:first)
            .map { |k, v| [k, v.map(&:last).inject(:+)] }
            .to_h
#=> { "Pomegranate" => 2, "Raspberry" => 9, "Miracle fruit" => 5}

我建议在Ruby的文档中查找ArrayHash中的每个方法,并在控制台中检查每个中间步骤返回的内容。

答案 2 :(得分:1)

这只是@ llya的解决方案#2的轻微变化。

product_name.each_index.with_object(Hash.new(0)) { |i,h|
  h[product_name[i]] += h[product_quantity[i]] }            .

答案 3 :(得分:-1)

我们不能这样做:

product_name.zip(product_quantity).to_h

似乎为我返回正确的结果?

相关问题