Iterate every month with date objects

Viewed 19292

So I have two ruby Date objects, and I want to iterate them every month. For example if I have Date.new(2008, 12) and Date.new(2009, 3), it would yield me 2008-12, 2009-1, 2009-2, 2009-3 (as Date objects of course). I tried using range, but it yields every day. I saw step method for Date however it only allows me to pass number of days (and each month has different number of those). Anyone have any ideas?

9 Answers

Welp, after lurking 15 years nearly this is my first stack overflow answer, I think.

start_date = Date.new(2000,12,15) # day is irrelevant and can be omitted
end_date = Date.new(2001,2,1). #same

(start_date.to_datetime..end_date.to_datetime).map{|d| [d.year, d.month]}.uniq.sort

# returns [[2000,12],[2001,1],[2001,2]]

(start_date.to_datetime..end_date.to_datetime).map{|d| Date.new(d.year, d.month)}.uniq.sort

# returns an array of date objects for the first day of any month in the span

Related