【问题标题】:i want to make a group Hash by keys and add values我想通过键创建一个组哈希并添加值
【发布时间】:2021-10-13 20:34:32
【问题描述】:

我有一个像这样的哈希

arr = { 93=>1, 92=>1, 91=>0,90=>0,29=>1340,28=>1245,27=>1231,26=>1102,25=>937,24=>688, 23=>540, 22=>360, 21=>270, 20=>143, 19=>77,18=>62,17=>39, 16=>42, 15=>27, 14=>12, 13=>4, 12=>2, 11=>2}

我想要结果

arr = {9 => sum values of Nineties, 2 => sum values of twenties, 1 =>  sum values of age teens}

【问题讨论】:

  • 你的哈希为什么叫arr
  • ArrayHash 是两种截然不同的对象。不要混淆它们!

标签: ruby-on-rails ruby group-by sum each


【解决方案1】:

我会使用each_with_object 方法。 (key, value) 这里是每个键/值对的解构,如93=>1hash 是存储结果的中间对象。

data.each_with_object({}) do |(key, value), hash|
  result_key = 
      case key
      when 10..19 then 1
      when 20..29 then 2
      when 90..99 then 9
      end
  next if result_key.nil?    
  hash[result_key] ||= 0
  hash[result_key] += value    
end

对于提供的输入,我得到了{9=>2, 2=>7856, 1=>267}

UPD

Holger Just 和 Stefan 在下面的 cmets 中提出了一个较短的解决方案。

data.each_with_object(Hash.new(0)) do |(key, value), hash|
  hash[key / 10] += value
end

使用Hash.new(0),初始对象将是具有默认值0的哈希

> hash = Hash.new(0)
=> {}
> hash[1]
=> 0

【讨论】:

  • 你可以使用result_key = key / 10
  • 其实如果把初始对象从{}改成Hash.new(0)整个块就可以缩减成hash[key / 10] += value
  • 对于给定的输入是
猜你喜欢
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 2021-10-21
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多