简体   繁体   中英

How to add hash value inside the hash and that contain in array in Ruby?

So I have an array that contain multiple hashes like:

[{"name"=>"a", "agg_value"=>"75.000000"}, {"name"=>"b", "agg_value"=>"25.000000"}, {"name"=>"a", "agg_value"=>"75.01000"}]

I want to convert this like following using ruby:

[{"name"=>"a", "agg_value"=>"150.000000"}, {"name"=>"b", "agg_value"=>"25.000000"}]

If the decimal aren't important, you could try something like that:

array = [{"name"=>"a", "agg_value"=>"75.000000"}, {"name"=>"b", "agg_value"=>"25.000000"}, {"name"=>"a", "agg_value"=>"75.01000"}]

array
  .group_by { |e| e['name'] }
  .map do |k, v|
    {
      'name' => k,
      'agg_value' => v.sum { |e| e['agg_value'].to_f }.to_s
    }
  end

If you want 6 decimals, then go for:

array
  .group_by { |e| e['name'] }
  .map do |k, v|
    {
      'name' => k,
      'agg_value' => '%.6f' % v.sum { |e| e['agg_value'].to_f }
    }
  end

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