Reputation: 25759
Given this hash in ruby:
h={
2010-03-01=>2
2010-03-02=>4
2010=03-03=>1
..
..
n days with working hours
}
where hash key is a date and hash value is an integer, how do I transform this hash into a new hash where keys are weeks/months/years (with aggregation)?
Let me show an example with weeks, the end result should look like:
h_weeks={7=>36, 8=>42, 9=>34 ..,..,n}
with months:
h_months={1=>170, 2=>180, 3=>146}
with years:
h_years={2009=>950, 2010=>446}
where key is a week number(month/year), and value is an aggregate of working hours within this week/month/year.
I'm writing a small working hours tracking application and would like to group this data.
Thanks.
Upvotes: 2
Views: 2837
Reputation: 44080
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
}
or, slightly more exotic:
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}}
Upvotes: 4