0

我已经使用强制来处理算术运算符:

class MyCustomClass

  def coerce( other )
    [MyCustomClass.new(other), self]
  end

end

这意味着我可以做到:

42 + MyCustomClass.new

我想知道是否存在允许我进行比较的类似机制(无需猴子修补Fixnum):

42 > MyCustomClass.new
4

1 回答 1

1

您只需要包含Comparable并定义<=>运算符:

class MyCustomClass
  include Comparable

  # ...

  def <=>(other)
    # e.g. compare self to fixnum and return -1, 0, 1
  end
end
于 2013-09-20T09:24:02.543 回答