0

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

{
    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
  }
}
4

2 回答 2

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
  }
]
于 2013-09-09T19:14:47.157 回答
0

像这样的东西?:

out = {}
h.each{|key,arr|
  total = arr.inject{|sum,entry|
      sum+=entry[:y]
  } 
  out[key]= {:y=>sum,:x=>"01/#{key}"}
}
于 2013-09-09T19:08:59.317 回答