There's some great discussion in the other answers, but it seems silly to iterate over all 365 days in each year just to get 12 date objects when it's not at all necessary.
Instead of iterating from from to to, calculate an integer number of months from each and then iterate over that range. Take a look:
from = Date.civil(2013, 7, 1)
to = Date.civil(2015, 11, 23)
from_mos = 12 * from.year + from.month - 1
to_mos = 12 * to.year + to.month - 1
dates = (from_mos..to_mos).map do |mos|
year, month = mos.divmod(12)
Date.civil(year, month + 1, 1)
end
Now dates is an Enumerable yielding a Date for the first day of each month, i.e. 2013-07-01, 2013-08-01, … 2015-11-01, which you can use as below;
dates.each do |date|
puts "Year #{date.year}, month #{date.month}"
end
# => Year 2013, month 7
# Year 2013, month 8
# ...
# Year 2015, month 10
# Year 2015, month 11
P.S. If you want to go to the trouble of defining a class or Struct, I recommend making it work directly with the Range API:
YearMonth = Struct.new(:year, :month) do
def succ
next_year, next_month = months.succ.divmod(12)
self.class.new(next_year, next_month + 1)
end
def <=>(other)
months <=> other.months
end
protected
def months
12 * year + month - 1
end
end
Now you can just do this:
from = YearMonth.new(2013, 7)
to = YearMonth.new(2015, 11)
(from..to).each do |ym|
puts "Year #{ym.year}, month #{ym.month}"
end