Forum: Ruby on Rails Useful code

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Luke I. (Guest)
on 2007-04-12 19:24
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

  def succ
    @range_distance ||= 1
    ret = self + @range_distance

You can then do things like:
t =
t2 = t + 4.days
(t..t2).each do |time|
  puts time.inspect

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
Luke I. (Guest)
on 2007-04-12 21:28
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
    yield self.end if self.end == val || options[:always_include_last]

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

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.
This topic is locked and can not be replied to.