I am having trouble figuring out the elegant way to add an array of hashes
[{:a=>1,:b=>2,:c=>3},{:a=>1,:b=>2,:c=>3},{:a=>1,:b=>2,:c=>3}]
should return
[{:a=>3,:b=>6,:c=>9}]
I know it would probably involve mapping/reducing, but I can't figure out the right syntax, doesn't help that ruby-doc dot org doesn't match my version
I am using 1.8.7
The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable.
We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
array.inject{|x,y| x.merge(y){|_,a,b| a + b}}
(verified on Ruby 1.8.7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With