3

我有一个按以下结构排列的记录数组:

[{"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}]

4

1 回答 1

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}]
于 2011-10-31T21:12:36.953 回答