Ruby on Rails - Hash of Arrays,group by和sum by many columns

时间:2015-02-08 09:44:24

标签: ruby-on-rails ruby arrays hash

我对此主题有类似的问题 Ruby on Rails - Hash of Arrays, group by and sum by column name

然而,我的问题是分组依据和多个列而不是一个。

例如:我的哈希

[
    {"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 arr, ["order","order1"], ["money","money1"]

这样的电话

我在合并中尝试了一个循环!但结果是错误的。 请教我解决这个案子。抱歉我的愚蠢思想。

1 个答案:

答案 0 :(得分:0)

使用Enumerable#group_by,您可以按orderorder1键迭代哈希数组。

然后合并哈希(通过总结moneymoney1条目):

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
}