2010-04-08 73 views
2

鉴于这种散列红宝石:组哈希

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} 

,其中关键是周数(月/年),价值是本周/月/年内的工作时间总和。

我正在写一个小型的工作时间跟踪应用程序,并想分组这些数据。

谢谢。

回答

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}} 
+0

姆拉登,你救了我的一天,谢谢。 – Valentin 2010-04-08 13:09:21