Ruby 1.8.7:group_by 与可枚举类型中的 sum

发布于 2024-12-12 19:52:07 字数 583 浏览 3 评论 0原文

我有一个记录数组,其结构如下:

[{"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、“总和=>125}, {“some_id”=> 1、“总和”=> 10}]

I have an array of records that is laid out in the following structure:

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

What's the best way using Ruby's group_by/inject/sum or whatever is available with Enumerable, to have that return an ordered array of hashes, where each hash is keyed by "some_id" and the value is the sum of all that id's "some_total" ordered by the id with the highest total at the beginning of the array? The results would look like the following:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我做我的改变 2024-12-19 19:52:07

功能方法:

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

Functional approach:

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}]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文