Ruby Time Functions Rock!!
February 4th, 2007
I haven’t had much cause to play with the Time module in Ruby until today. I have used Time.now quite a bit, but not too much more than that. However, today I had to find the last 6 months names to label a graph and in a short period of time I had come up with this:
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] labels = [] 0.upto(5) do |x| labels.unshift(months[Time.now.months_ago(x).month-1]) end
Which I think is pretty neat, especially remembering what a pain it was in Perl last time I had to do it….....
November 25th, 2007 at 11:18 PM You may already know this, but you could replace your own array of month abbreviations with the Date module's ABBR_MONTHNAMES constant... require 'date' months = Date::ABBR_MONTHNAMES The first element is 'nil', resulting in the index matching the month numbers (1 = 'Jan', etc.). I frequently work with this array and have found this constant handy.
November 25th, 2007 at 11:18 PM Hi Mully, cheers for that. I have to admit I didn't know, but I do now. That makes it even neater: Thanks, Scott.
November 25th, 2007 at 11:18 PM http://chronic.rubyforge.org/ I've been using this to spice time handling up a bit. Pretty cool stuff.
November 25th, 2007 at 11:18 PM Hi Blake, Yep I've had a little play with chronic, seems to be great with certain stuff ('in an hour', 'yesterday', etc) but not so good for things like 'the first day of next month', 'the first day of last month'. But still a great idea. I need to use it more to understand how to get the best out of it I think. Cheers Scott.
November 25th, 2007 at 11:18 PM Hey, you are sitting next to me at FoWA. Here's a more idiomatic way of doing the same thing: (0..5).collect {|months_ago| Time.now.months_ago(months_ago).strftime("%b") }.reverse