使用唯一的object_id对属性数组求和

时间:2016-06-20 22:16:01

标签: ruby

说我有以下对象数组:

objects = [{id: 1, installs: 21}, {id: 2, installs: 10}, {id:1, installs: 11}, {id:3, installs:5}]

我想对同一install的所有id值求和。最好的方法是什么?

2 个答案:

答案 0 :(得分:4)

objects = [{id: 1, installs: 21}, {id: 2, installs: 10}, {id: 1, installs: 11}, {id: 3, installs: 5}]

sums = Hash.new(0)  # sums returns 0 for an unknown key
objects.each{|h| sums[h[:id]] += h[:installs]}
p sums  # => {1=>32, 2=>10, 3=>5}

答案 1 :(得分:0)

sorted = objects.group_by{|x|x[:id]}
sorted.map{|x|x[1].inject(0){|sum, x| sum + x[:installs]}}