Ruby:获取嵌套哈希值的总和

时间:2013-09-09 19:00:38

标签: ruby hash

我有一个按年份分组的数组哈希,如下:

{
    1979 => [
        [0] {
             :x => "12/79",
             :y => 71,
            :date => Sat, 01 Dec 1979
        }
    ],
    1980 => [
        [0] {
            :x => "01/80",
            :y => 1680,
            :date => Tue, 01 Jan 1980
        },
        [1] {
            :x => "08/80",
            :y => 1,
            :date => Fri, 01 Aug 1980
        }
    ]
}

我需要一种方法来按年计算所有[:y]个键值,然后将新值推送到另一个哈希值(或折叠相同的哈希值),我在其中设置:x的值

输出看起来像这样:

{
  { 
    :x => "1/79",
    :y => 71,
  },
  {
    :x => "1/1980",
    :y => 1681
  }
}

2 个答案:

答案 0 :(得分:2)

输入散列更正:

foo = {
    1979 => [
        {
             :x => "12/79",
             :y => 71,
            :date => Sat, 01 Dec 1979
        }
    ],
    1980 => [
        {
            :x => "01/80",
            :y => 1680,
            :date => Tue, 01 Jan 1980
        },
        {
            :x => "08/80",
            :y => 1,
            :date => Fri, 01 Aug 1980
        }
    ]
}

bar = foo.collect { |k,v| { :x => "1/#{k.to_s}", :y => v.inject(0) { |s, vv| s + vv[:y]}} }

bar是:

[
  { 
    :x => "1/79",
    :y => 71,
  },
  {
    :x => "1/1980",
    :y => 1681
  }
]

答案 1 :(得分:0)

这样的事情?:

out = {}
h.each{|key,arr|
  total = arr.inject{|sum,entry|
      sum+=entry[:y]
  } 
  out[key]= {:y=>sum,:x=>"01/#{key}"}
}