Ari53nN3o Ari53nN3o - 13 days ago 5
Ruby Question

How do you implement 1.day.ago in Ruby

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.

Answer

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

Comments