Ruby 1.8.7:group_by 与可枚举类型中的 sum
我有一个记录数组,其结构如下:
[{"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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
功能方法:
Functional approach: