Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing the values of an array of hashes in Ruby

Tags:

ruby

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

like image 600
Christopher Avatar asked Feb 21 '10 06:02

Christopher


People also ask

How do you sum all the numbers in an array in Ruby?

The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable.

How do you combine hashes in Ruby?

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.

What is array of hashes in Ruby?

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.


1 Answers

array.inject{|x,y| x.merge(y){|_,a,b| a + b}}

(verified on Ruby 1.8.7)

like image 124
Peter Avatar answered Sep 23 '22 01:09

Peter