Iterating through dates.

by Rabbit

Indirectly, someone was asking how to iterate through dates in Ruby. Here’s one way:

(Date.today..Date.today + 10).each { |date| puts date }
# 2007-06-05
# 2007-06-06
# ...
# 2007-06-14
# 2007-06-15

You can do the same thing with Time objects, but be aware it iterates over seconds, not days.

(Time.now..Time.now + 10).each { |time| puts time }
# Tue Jun 05 19:22:19 PDT 2007
# Tue Jun 05 19:22:20 PDT 2007
# ...
# Tue Jun 05 19:22:28 PDT 2007
# Tue Jun 05 19:22:29 PDT 2007

Notice the timezone, too. Time objects, even if they are the same time, are not equal (== or eql?) if the timezone is different. I’ve been bitten by this a few times! It sucks.