我有一个按年份分组的数组哈希,如下:
{
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
}
}
答案 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}"}
}