tags:

views:

62

answers:

1

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

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

(verified on Ruby 1.8.7)

Peter
This is pretty cool, although I don't know why the merge works without injecting an empty hash...
hurikhan77
@hurikhan77 the first inject takes place initialized with the first item of array -- not with an empty element.
Peter
@Peter what does the underscore do as the first block parameter for merge?
Beerlington
@Beerlington, it's just a variable I don't want to use. It's actually a Python convention to name it that. (The three parameters passed to the block are key, x value, y value.)
Peter
@Peter, interesting. I like it, thanks!
Beerlington
@Peter i think the underscore is more a haskell convention (from its pattern matching) which was also taken by python...
hurikhan77
@hurikhan77 ah, interesting - thanks. haskell's on the list to add to the repertoire at some point.
Peter