Group hashes by keys and sum the values

前端 未结 5 2119
情话喂你
情话喂你 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:00

    If have two hashes with multiple keys:

    h1 = { "Vegetable" => 10, "Dry Goods" => 2 }
    h2 = { "Dry Goods" => 3, "Vegetable" => 5 }
    details = {}
    (h1.keys | h2.keys).each do |key|
      details[key] = h1[key].to_i + h2[key].to_i
    end
    details
    

提交回复
热议问题