How to sum values in an array with different hash

I want to sum the total values of the same items in an array.

I have a array as

[{"a"=>1},{"b"=>2},{"c"=>3},{"a"=>2},{"b"=>4}]

I want to get the result as

[{"a"=>3},{"b"=>6},{"c"=>3}]

Which method can do it?

array =[{"a"=>1},{"b"=>2},{"c"=>3},{"a"=>2},{"b"=>4}]
array.reduce({}) { |hash, acc| acc.merge(hash) {|_k, old, new| old + new } }
# => {"b"=>6, "a"=>3, "c"=>3}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章