Ruby on Rails - hash of arrays, grouped by and by column name
I have the following hash array:
[{"idx" => "1234", "account" => "abde", "money" => "4.00", "order" => "00001"}, {"idx" => "1235", " account "=>" abde "," money "=>" 2.00 "," order "=>" 00001 "}, {" idx "=>" 1235 "," account "=>" abde "," money "= > "3.00", "Order" => "00002"}]
How and how sql does it, I would like to take this hash array and group it by order number so that it looks as if the order 00001 has been grouped and it sums the money up to 6.00:
[{"idx" => "1234", "account" => "abde", "money" => "6.00", "order" => "00001"}, {"idx" => "1234", " account "=>" abde "," money "=>" 3.00 "," Order "=>" 00002 "}]
Thanks.
you can create your own method, for example:
def group_hashes arr, group_field, sum_field arr.inject({}) do |res, h| (res[h[group_field]] ||= {}).merge!(h) do |key, oldval, newval| key.eql?(sum_field) ? (oldval.to_f + newval.to_f).to_s : oldval end res end.values end call group_hashes arr, "order", "money" using an example hash array:
[{"idx"=>"1234", "account"=>"abde", "money"=>"6.0", "order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "money"=>"3.00", "order"=>"00002"}]