Ruby on Rails的 - 通过阵列,组​​哈希和多列通过总结 [英] Ruby on Rails - Hash of Arrays, group by and sum by with many columns

查看:143
本文介绍了Ruby on Rails的 - 通过阵列,组​​哈希和多列通过总结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题类似的问题
<一href=\"http://stackoverflow.com/questions/8500280/ruby-on-rails-hash-of-arrays-group-by-and-sum-by-column-name\">Ruby on Rails的 - 通过阵列,组​​哈希和金额列名

I have a similar problem with this topic Ruby on Rails - Hash of Arrays, group by and sum by column name

不过,我的问题是,通过和群组多列,而不是一个通过总结

However, my problem is that group by and sum by with many columns instead of one.

例如:我的哈希值

[
    {"idx"=>"1234", "account"=>"abde", "money"=>"4.00", "money1"=>"1.00", "order"=>"00001", "order1"=>"1"},
    {"idx"=>"1235", "account"=>"abde", "money"=>"2.00", "money1"=>"1.00", "order"=>"00001", "order1"=>"1"},
    {"idx"=>"1235", "account"=>"abde", "money"=>"3.00", "money1"=>"1.00", "order"=>"00002", "order1"=>"2"}
]

这样的结果。

[
    {"idx"=>"1234", "account"=>"abde", "money"=>"6.00", "money1"=>"2.00","order"=>"00001", "order1"=>"1"},
    {"idx"=>"1234", "account"=>"abde", "money"=>"3.00", "money1"=>"1.00","order"=>"00002", "order1"=>"2"}
]

这样的调用 group_hashes改编,[秩序,order1],[钱,MONEY1]

我试过一个循环内合并!但是,结果是错误的。
请告诉我解决这个情况。对不起,我的心中蠢

I tried a loop inside merge! However, the result is wrong. Please teach me solve this case. Sorry for my stupid mind.

推荐答案

Usnig的 可枚举#GROUP_BY ,则可以通过迭代订单,<$ C组合哈希数组$ C> order1 键。

Usnig Enumerable#group_by, you can iterate arrays of hashes grouped by order, order1 key.

然后合并哈希(通过总结 MONEY1 项):

Then merge hashes (by summing up money, money1 entries):

a = [
  {"idx"=>"1234", "account"=>"abde", "money"=>"4.00", "money1"=>"1.00", "order"=>"00001", "order1"=>"1"},
  {"idx"=>"1235", "account"=>"abde", "money"=>"2.00", "money1"=>"1.00", "order"=>"00001", "order1"=>"1"},
  {"idx"=>"1235", "account"=>"abde", "money"=>"3.00", "money1"=>"1.00", "order"=>"00002", "order1"=>"2"}
]
a.group_by { |x| x.values_at('order', 'order1') }.map {|key, hashes|
  result = hashes[0].clone
  ['money', 'money1'].each { |key|
    result[key] = hashes.inject(0) { |s, x| s + x[key].to_f }
  }
  result
}
# => [{"idx"=>"1234", "account"=>"abde", "money"=>6.0, "money1"=>2.0, "order"=>"00001", "order1"=>"1"},
#     {"idx"=>"1235", "account"=>"abde", "money"=>3.0, "money1"=>1.0, "order"=>"00002", "order1"=>"2"}]


group_keys = ['order', 'order1']
sum_keys = ['money', 'money1']
a.group_by { |x| x.values_at(*group_keys) }.map {|key, hashes|
  result = hashes[0].clone
  sum_keys.each { |key|
    result[key] = hashes.inject(0) { |s, x| s + x[key].to_f }
  }
  result
}

这篇关于Ruby on Rails的 - 通过阵列,组​​哈希和多列通过总结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆