Question

As you guys might have already guessed it, it's an interview question. But I'm not gonna disclose which company. I was asked to implement

1.day.ago

in Ruby. This is a date helper in Rails but this functionality doesn't exist in Ruby.

Was it helpful?

Solution

All it does* is return the number of seconds in a day, multiplied by self:

class Fixnum
  def day
    self * (60 * 60 * 24) # seconds * minutes * hours
  end
end


# 10.days => 'self' is 10, so 10 * 60 * 60 * 24

Then, .ago subtracts that many seconds from Time.now:

class Fixnum
  def ago
    Time.now - self
  end
end

# 10.days.ago == Time.now - (10 * 60 * 60 * 24) 

*This is actually not all it does; in reality it returns a proxy object which represents the given duration. The math is also significantly more complex

OTHER TIPS

Here's one way to do it:

Time.now-86400
#=> 2014-01-26 16:54:07 -0500

86400 is the number of seconds in a day.

Disclaimer: This example obviously does not include shifts in time due to daylight savings. (Use at your own peril.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top