Rails中的日期/时间比较

gsm*_*oza 2 ruby ruby-on-rails

我希望能够在Rails中比较Dates和Times,而无需始终调用to_time或to_date方法.所以我写了下面的代码:

class Date
  def ==(other)
    if other.kind_of?(Time)
      self.to_time == other
    else
      super(other)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我知道有一种简单的方法可以写这个,这样我就可以为>,<,> =,<=和<=>做这个工作.但我忘记了:P有什么想法吗?

Chu*_*eow 5

使任何旧Ruby类可比的最简单方法是实现<=>实例方法并包含Comparable mixin.您将免费获得>,<,> =,<=,==等方法.

解决此问题的一种方法是重新打开日期和时间类,include Comparable<=>在必要时重新定义其方法以执行日期/时间转换(<=>否则返回原始定义).