Let's say I had a Ruby Array of Date
s like:
2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:
{
2011 => {
1 => [2011-01-20, 2011-01-23],
2 => [2011-02-01, 2011-02-15],
3 => [2011-03-21],
}
}
I can do this by iterating over everything and extracting years, months and so on, then comining them.
Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?
I noticed you have changed month names into numbers, so you may want to replace
d.strftime('%B')
above withd.month
or whatever else.Here's a step-by-step explanation:
You essentially want two-level grouping: first level by year, second by month. Ruby has very useful method
group_by
, which groups elements by given expression (a block). So: first part is grouping original array byyear
:That gives us first level: keys are years, values arrays of dates with given year. But we still need to group the second level: that's why we map by-year hash - to group its values by
month
. Let's for start forgetstrftime
and say that we're grouping byd.month
:That way we got our second level grouping. Instead of array of all dates in a year, now we have hash whose keys are months, and values arrays of dates for a given month.
The only problem we have is that
map
returns an array and not a hash. Thats why we "surround" whole expression byHash[]
, which makes a hash out of array of pairs, in our case pairs[year, hash_of_dates_by_month]
.Sorry if the explanation sounds confusing, I found harder to explain functional expressions than imperative, because of the nesting. :(
This gets you pretty close, you just need to change the numerical month number into a textual month name: