Useful code

Just wrote this little snippet as I need to occasionally parse over a
range of time at given intervals. Thought someone else might find it
useful, didn’t know where else to put it.

class Time
def set_range_distance(seconds)
@range_distance = seconds
end

def succ
@range_distance ||= 1
ret = self + @range_distance
ret.set_range_distance(@range_distance)
ret
end
end

You can then do things like:
t = Time.now
t2 = t + 4.days
t.set_range_distance(2.hours)
(t…t2).each do |time|
puts time.inspect
end

which will give output of
Thu Apr 12 10:20:07 -0500 2007
Thu Apr 12 12:20:07 -0500 2007
Thu Apr 12 14:20:07 -0500 2007

So, I was using what I wrote above, and realized that, should the ending
value of your time range not fall exactly on the interval specified, it
will only show the last interval before the end of the range… and
sometimes, that’s not what I want. So, I did this

class Range
def each(options = {}, &block)
val = self.begin
while val < self.end
yield val
val = val.succ
end
yield self.end if self.end == val || options[:always_include_last]
end
end

Now, when I’m doing my iteration over the range, I can specify
range.each :always_include_last => true do |time|
#do stuff with the time here
end

And it will always include the last value… even if it’s only 5 minutes
from your last one, and you told it to do 30 minute intervals.