andialles andialles - 8 months ago 24
Ruby Question

Ruby: Grouping a date range by year and month

I am creating a range for each month in another range. For this I need the beginning and the end of every month in my range.

At the moment I'm doing this, which obviously doesn't work for ranges longer than a year.

example_range = (
example_range.group_by(&:month).each { |_, month| month.first..month.last }

I also tried this, but it segfaults...

example_range.group_by(&:year).map{ |ary| ary.group_by(&:month)}`

Does anyone know a more beautiful (or at least working) way of doing this?


The best solution I think is this:

example_range.group_by {|date| date.month.to_s + "-" + date.year.to_s}

You can adjust the way you need.