本文介绍了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:

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",订单"=>00002"}]

谢谢.

推荐答案

您可以为此创建自己的方法,例如:

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

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

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

这篇关于Ruby on Rails - 数组散列,按列名分组和求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:59