Ruby on Rails - Hash of Arrays, group by and sum b

2019-08-07 11:24发布

问题:

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.

For example: my hashes

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

The result like this

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

a call like this group_hashes arr, ["order","order1"], ["money","money1"]

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

回答1:

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

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
}