andialles
andialles

Reputation: 185

Ruby: Grouping a date range by year and month

I am creating a range for each month in my example range.

example_range = (Time.zone.today..2.years.from_now)

Output should look like so:

=> [Wed, 03 Aug 2016..Wed, 31 Aug 2016, Thu, 01 Sep 2016..Fri,
30 Sep 2016, Sat, 01 Oct 2016..Mon, 03 Oct 2016, ...]  

At the moment I'm doing this, which doesn't work for ranges longer than a year, because the grouping will put January '16 and January '17 in one group.

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

I also tried this, but ruby segfaults on this for some reason...

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?

Upvotes: 3

Views: 1497

Answers (2)

hibariya
hibariya

Reputation: 390

How is this:

example_range.group_by {|date| [date.year, date.month] }.map {|_, month| month.first..month.last }

If you are using Active Support (Rails), this will also work:

example_range.group_by(&:beginning_of_month).map {|_, month| month.first..month.last }

Upvotes: 6

rneves
rneves

Reputation: 2083

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.

Upvotes: 0

Related Questions