Iterate over Ruby Time object with delta

Prior to 1.9, you could use Range#step:

(start_time..end_time).step(3600) do |hour|
  # ...

However, this strategy is quite slow since it would call Time#succ 3600 times. Instead,
as pointed out by dolzenko in his answer, a more efficient solution is to use a simple loop:

hour = start_time
while hour < end_time
  # ...
  hour += 3600

If you’re using Rails you can replace 3600 with 1.hour, which is significantly more readable.

Leave a Comment