开发者

Summing the values of an array of hashes in Ruby

开发者 https://www.devze.com 2022-12-20 16:08 出处:网络
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}]

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

精彩评论

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