简体   繁体   中英

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

I have the following array of hashes:

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

Like how sql does it, I'd like to take that array of hashes and group it by the order number so that it results like this where order 00001 is grouped and it sum the money to 6.00:

[{"idx"=>"1234", "account"=>"abde", "money"=>"6.00", "order"=>"00001"}, {"idx"=>"1234", "account"=>"abde", "money"=>"3.00", "order"=>"00002"}]

Thanks.

you can make your own method for that, something like:

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

a call group_hashes arr, "order", "money" on you array of hashes example returns:

[{"idx"=>"1234", "account"=>"abde", "money"=>"6.0", "order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "money"=>"3.00", "order"=>"00002"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM