# Useful code

**URL:** <https://www.ruby-forum.com/t/useful-code/91825>\
**Category:** Rails\
**Created:** [April 12, 2007, 5:24pm UTC](https://www.ruby-forum.com/t/useful-code/91825 "2007-04-12T17:24:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![technodolt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e99b99/32.png) [@technodolt](https://www.ruby-forum.com/u/technodolt)\
**Post date:** [April 12, 2007, 5:24pm UTC](https://www.ruby-forum.com/t/useful-code/91825/1 "2007-04-12T17:24:07Z")

</div>

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  
…

---

<div class="post-metadata">

**Author:** ![technodolt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e99b99/32.png) [@technodolt](https://www.ruby-forum.com/u/technodolt)\
**Post date:** [April 12, 2007, 7:28pm UTC](https://www.ruby-forum.com/t/useful-code/91825/2 "2007-04-12T19:28:06Z")

</div>

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.
