Iterating Through The Last 30 Days with Ruby on Rails

Posted on June 10, 2007

Recently, I attempted to create a loop in Ruby on Rails that iterated through the last month worth of dates. Stupidly, I just typed in the following code, and tried to run it… (you need to require ActiveSupport for month.ago to work.

# This code does not work
1.month.ago.step(Time.now, 1.day) { |d|
  print d.day,"\\n"
}

Unfortunately, that doesn’t work, because ActiveSupport returns a Time class value for month.ago. Ruby’s Time class doesn’t define a step method. So, being lazy, I just casted the time to an integer with to_i, and constructed the following loop which does work.

1.month.ago.to_i.step(Time.now.to_i,1.day.to_i) { |d|
   print Time.at(d).day,"\\n"
}

Later on, I learned that Date’s have a step class. So, I simplified the loop.

1.month.ago.to_date.step(Time.now.to_date, 1.day) { |d|
    print d.day,"\\n"
}

It seems like there should be an easier way to do this though. Does anyone have a better idea?

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. crayz Fri, 28 Sep 2007 17:36:21 UTC

    Try this, pretty close to copy/paste from rubinius code for ints:

    http://pastie.caboo.se/101886

Comments