说我有以下对象数组:
objects = [{id: 1, installs: 21}, {id: 2, installs: 10}, {id:1, installs: 11}, {id:3, installs:5}]
我想对同一install
的所有id
值求和。最好的方法是什么?
答案 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]}}