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

时间:2011-12-14 06:24:08

标签: ruby-on-rails

我有以下哈希数组:

  

[{“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”,   “命令”=> “中00002”}]

就像sql的做法一样,我想把这个哈希数组并按顺序编号分组,这样就可以得到这样的结果,其中00001的订单被分组,并将钱加到6.00:

  

[{“idx”=>“1234”,“account”=>“abde”,“money”=>“6.00”,   “order”=>“00001”},{“idx”=>“1234”,“account”=>“abde”,“money”=>“3.00”,   “命令”=> “中00002”}]

感谢。

1 个答案:

答案 0 :(得分:3)

您可以为此制作自己的方法,例如:

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

对哈希示例数组的调用group_hashes arr, "order", "money"返回:

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