开发者

Summing the values of an array of hashes in 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


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

(verified on Ruby 1.8.7)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜