【发布时间】:2022-11-17 22:31:30
【问题描述】:
我有以下哈希:
{"shape":[
{"key":"0000round","total_amount":"54679110.10","name":"Round","count":100},
{"key":"0001square","total_amount":"4074837.00","name":"Square","count":200},
{"key":"0003rectangle","total_amount":"6114261.00","name":"Rectangle","count":150},
{"key":"0008round","total_amount":"6425948.50","name":"Round","count":620},
{"key":"0004square","total_amount":"5009297.50","name":"Square","count":440}
]}
我想对总金额求和并计算一些重复值,例如 0000round 和 0008round。
在这种情况下,uniq key 将是Name
所以Name=Round对于Square有两个相似的值。
到目前为止我尝试了什么:
temp_hash = Hash.new(nil)
raw_hash['shape'].each do |shape|
if temp_hash[shape['name']].present?
temp_hash[shape['name']]['total_amount'] = temp_hash[shape['name']]['total_amount'].to_f + shape['total_amount'].to_f
temp_hash[shape['name']]['count'] = temp_hash[shape['name']]['count'].to_i + shape['count'].to_i
temp_hash[shape['name']]['key'] = [temp_hash[shape['name']]['key'] , shape['key']].flatten
else
temp_hash[shape['name']] = shape
end
raw_hash['shape'] = temp_hash.values
end
输出是
{"shape"=>[
{"key"=>["0000round", "0004round"],"total_amount"=>59688407.6,"name"=>"Round","count"=>7437},
{"key"=>"0001princess","total_amount"=>"4074837.00","name"=>"Princess","count"=>810},
{"key"=>["0003oval", "0008oval"],"total_amount"=>12540209.5,"name"=>"Oval","count"=>1460}]}
有更好的方法吗?
【问题讨论】: