Wednesday, 19 September 2007

methods in_time

On the subject of "why isn't this in Ruby already?". I've written up a set of conversion methods that I felt sure were there already, except that I couldn't find them anywhere.

class Numeric
  # assumes i am expressed in seconds - converts me to minutes
  def in_minutes
    self / 60
  end
  # assumes i am expressed in seconds - converts me to hours
  def in_hours
    self / 3600
  end
  # assumes i am expressed in seconds - converts me to days
  def in_days
    self / (3600 * 24)
  end
end

So now I can do things like: 3600.in_hours, but also the more useful: (prevTime - Time.now).in_days

5 comments:

Teflon Ted said...

# assumes i am expressed in seconds

That's a lot of assumptions.

Why not code it to work like this:

3600.seconds.in_hours

3600.days.in_hours

?

Taryn said...

Yup, that'll work too.
I noticed that Rails already has the "days", "hours" and "seconds" methods, so I just added the methods I couldn't find.

Taryn said...

In fact, that's why my methods assume they're in seconds - because "days" just converts the number into the equivalent number of seconds.

Anonymous said...

rails has a couple of date helpers but I do think these methods would be pretty helpful

Taryn East said...

you're probably thinking of these ones: http://api.rubyonrails.org/classes/Integer.html

But you may also note the date on my post... 2007 ;)
Some of those date helpers were only developed in Rails in 2009