我想 group_by 多个键:orders、idx、account 等。下面的代码是Ruby on Rails - Hash of Arrays, group by and sum by column name的修改版本。谁能推荐一种对多个键进行分组并对多个值求和的方法?
例如,在下面的代码中,我只对“订单”进行分组。我想按订单、idx 和帐户分组。
group_hashes some_array, ["order","idx","account"] ["money","amt"]
对比
group_hashes some_array, "order", "money","amt"
代码:
some_array=[{"idx"=>"1234", "account"=>"abde", "amt"=>"2", "money"=>"4.00",
"order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "amt"=>"2" ,
"money"=>"2.00", "order"=>"00001"}, {"idx"=>"1235",
"account"=>"abde", "amt"=>"2" , "money"=>"3.00", "order"=>"00002"}] # => [{"idx"=>"1234", "account"=>"abde", "amt"=>"2", "money"=>"4.00", "order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "amt"=>"2", "money"=>"2.00", "order"=>"00001"}, {"idx"=>"1235", "account"...
#group_hashes arr, "order", "money"
def group_hashes arr, group_field, *sum_field
arr.inject({}) do |res, h|
(res[h[group_field]] ||= {}).merge!(h) do |key, oldval, newval|
sum_field.include?(key) ? (oldval.to_f + newval.to_f).to_s : oldval # => "1234", "abde", "4.0", "6.0", "00001"
end # => {"idx"=>"1234", "account"=>"abde", "amt"=>"2", "money"=>"4.00", "order"=>"00001"}, {"idx"=>"1234", "account"=>"abde", "amt"=>"4.0", "money"=>"6.0", "order"=>"00001"}, {"idx"=>"1235", "account"...
res # => {"00001"=>{"idx"=>"1234", "account"=>"abde", "amt"=>"2", "money"=>"4.00", "order"=>"00001"}}, {"00001"=>{"idx"=>"1234", "account"=>"abde", "amt"=>"4.0", "money"=>"6.0", "order"=>"00001"}}, {"0...
end.values # => [{"idx"=>"1234", "account"=>"abde", "amt"=>"4.0", "money"=>"6.0", "order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "amt"=>"2", "money"=>"3.00", "order"=>"00002"}]
end # => nil
group_hashes some_array, "order", "money","amt" # => [{"idx"=>"1234", "account"=>"abde", "amt"=>"4.0", "money"=>"6.0", "order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "amt"=>"2", "money"=>"3.00", "order"=>"00002"}]
输入的预期输出:
input =[ {"idx"=>"1234", "account"=>"abde", "amt"=>"2", "money"=>"4.00", "order"=>"00001"},
{"idx"=>"1234", "account"=>"abde", "amt"=>"2" ,"money"=>"2.00", "order"=>"00001"},
{"idx"=>"1235", "account"=>"abde", "amt"=>"2" , "money"=>"3.00", "order"=>"00002"},
{"idx"=>"1235", "account"=>"abde", "amt"=>"3", "money"=>"4.00", "order"=>"00002"},
{"idx"=>"1234", "account"=>"ddd", "amt"=>"2", "money"=>"4.00", "order"=>"00003"},
{"idx"=>"1234", "account"=>"ddd", "amt"=>"2", "money"=>"4.00", "order"=>"00003"}
]
output =[ {"idx"=>"1234", "account"=>"abde", "amt"=>"4", "money"=>"6.00", "order"=>"00001"},
{"idx"=>"1235", "account"=>"abde", "amt"=>"5" , "money"=>"7.00", "order"=>"00002"},
{"idx"=>"1234", "account"=>"ddd", "amt"=>"4", "money"=>"8.00", "order"=>"00003"},
]