andy lindeman . com


Iterating Through Time With Rails

Be sure to read the follow up post where I analyze this a bit more and make better recommendations.

I just learned this neat trick from @rjspotter.

# Could also use Enumerable#map with Time.at
Range.new(Time.now.to_i, 5.days.from_now.to_i).step(1.day) do |seconds_since_epoch|
  time = Time.at(seconds_since_epoch)
  puts time
end

Right now, for instance, that outputs:

Fri Jan 21 15:25:32 -0600 2011
Sat Jan 22 15:25:32 -0600 2011
Sun Jan 23 15:25:32 -0600 2011
Mon Jan 24 15:25:32 -0600 2011
Tue Jan 25 15:25:32 -0600 2011
Wed Jan 26 15:25:32 -0600 2011

Replace days with hours, minutes, weeks, etc…

Notably, this uses Range#step from Ruby core and ActiveSupport’s monkey patching of Numeric from Rails.

While the #to_i calls look a bit unappealing, it’s important that Range#step is called over numbers, or else it would have to call #succ 86400 times between iterations!

— Jan 21, 2011
blog comments powered by Disqus

subscribe

Subscribe to RSS feed

© Andy Lindeman | Icons from silk | [source on github] | [validate as html5]