简体   繁体   中英

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}}

(在Ruby 1.8.7上验证)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM