Ruby 1.8.7:group_by,其中sum为可枚举类型

时间:2011-10-31 21:04:05

标签: ruby enumerable

我有一系列记录,这些记录在以下结构中列出:

[{"some_id" => 2, "some_total => 250}, {"some_id" => 2, "some_total" => 100}, {"some_id" => 3, "some_total" => 50}, {"some_id" => 3, "some_total" => 50}, {"some_id" => 3, "some_total" => 25}, {"some_id" => 1, "some_total" => 10}]

使用Ruby的group_by / inject / sum或Enumerable可用的任何东西的最佳方法是返回一个有序的哈希数组,其中每个哈希都用“some_id”键入,值是所有id的总和“some_total”由id排序,数组开头的总数最高?结果如下所示:

[{"some_id" => 2, "sum" => 350}, {"some_id" => 3, "sum => 125}, {"some_id" => 1, "sum" => 10}]

1 个答案:

答案 0 :(得分:5)

功能方法:

hs.group_by { |h| h["some_id"] }.map do |id, hs|
  sum = hs.map { |h| h["some_total"] }.inject(:+) 
  {:some_id => id, :sum => sum}
end.sort_by { |h| -h[:sum] } 

#=> [{:some_id=>2, :sum=>350}, 
#    {:some_id=>3, :sum=>125}, 
#    {:some_id=>1, :sum=>10}]