Group hashes by keys and sum the values

前端 未结 5 2118
情话喂你
情话喂你 2020-11-27 03:50

I have an array of hashes:

[{\"Vegetable\"=>10}, {\"Vegetable\"=>5}, {\"Dry Goods\"=>3>}, {\"Dry Goods\"=>2}]

I need to use

5条回答
  •  我在风中等你
    2020-11-27 04:19

    ar = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3}, {"Dry Goods"=>2}]
    p ar.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v + new_v}}
    #=> {"Vegetable"=>15, "Dry Goods"=>5}
    

    Hash.merge with a block runs the block when it finds a duplicate; inject without a initial memo treats the first element of the array as memo, which is fine here.

提交回复
热议问题