如何根据 ruby 中的类型和名称键求和? (ruby 哈希数组)

How to find sum on basis of type and name key in ruby? (ruby array of hashes)

如何根据 ruby 中的类型和名称键求和? (ruby 哈希数组)

eatables = [{type: "fruit", name: "apple", count: 2},
            {type: "vegetable", name: "pumpkin", count: 3},
            {type: 'fruit', name: 'apple', count: 1},
            {type: "vegetable", name: "pumpkin", count: 2}]

期望的输出

[{type: "fruit", name: "apple", count: 3},
 {type: "vegetable", name: "pumpkin", count: 5}]

这类问题可以用 reduce

来解决
output = eatables.reduce({}) do |hsh, current|
             if hsh.has_key?(current[:type]+current[:name])
                 hsh[current[:type]+current[:name]][:count] += current[:count]
             else 
                hsh[current[:type]+current[:name]] = current
             end
             hsh
         end.values
eatables.group_by { |h| h.slice(:name, :type) }
        .map { |key, grouped| key.merge(count: grouped.sum{ |h| h[:count] }) }

第一个操作根据名称和类型将数组分成几组。

{{:name=>"apple", :type=>"fruit"}=>[{:type=>"fruit", :name=>"apple", :count=>2}, {:type=>"fruit", :name=>"apple", :count=>1}], {:name=>"pumpkin", :type=>"vegetable"}=>[{:type=>"vegetable", :name=>"pumpkin", :count=>3}, {:type=>"vegetable", :name=>"pumpkin", :count=>2}]}

然后我们映射该散列和 return 一个散列数组,其类型、名称和总和输出:

=> [{:name=>"apple", :type=>"fruit", :count=>3}, {:name=>"pumpkin", :type=>"vegetable", :count=>5}]
eatables.inject(Hash.new(0)) { |h, item|
  h[item.slice(:type, :name)] += item[:count]
  h
}.map { |k, v|
  {**k, count: v}
}