在ruby中给出这个哈希:
h={
2010-03-01=>2
2010-03-02=>4
2010=03-03=>1
..
..
n days with working hours
}
其中散列键是日期,散列值是整数,如何将此散列转换为新的散列,其中键是周/月/年(带聚合)?
让我举几个例子,最终结果如下:
h_weeks={7=>36, 8=>42, 9=>34 ..,..,n}
有几个月:
h_months={1=>170, 2=>180, 3=>146}
多年:
h_years={2009=>950, 2010=>446}
其中key是周数(月/年),value是本周/月/年内工时的总和。
我正在编写一个小工时跟踪应用程序,并希望对这些数据进行分组。
感谢。
答案 0 :(得分:4)
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}}