h = {
Date.parse('2010-04-02') => 3,
Date.parse('2010-05-03') => 5,
Date.parse('2009-04-03') => 6
}
by_year = Hash.new(0)
by_month = Hash.new(0)
by_week = Hash.new(0)
h.each{|d,v|
by_year[d.year] += v
by_month[d.month] += v
by_week[d.cweek] += v
}
或者,稍微有点异国情调:
aggregates = {}
h.each{|d,v|
[:year, :month, :cweek].each{|period|
aggregates[period] ||= Hash.new(0)
aggregates[period][d.send(period)] += v
}
}
p aggregates
#=>{:year=>{2010=>8, 2009=>6}, :month=>{4=>9, 5=>5}, :cweek=>{13=>3, 18=>5, 14=>6}}