andialles andialles - 4 months ago 10
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 = (Time.zone.today..2.years.from_now)
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?

Answer

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.

Comments