【问题标题】:How to allow comparison between Fixnum and custom class?如何允许在 Fixnum 和自定义类之间进行比较?
【发布时间】:2013-09-20 09:13:53
【问题描述】:

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

class MyCustomClass

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

end

这意味着我可以做到:

42 + MyCustomClass.new

我想知道是否存在类似的机制,它可以让我进行比较(无需猴子修补 Fixnum):

42 > MyCustomClass.new

【问题讨论】:

    标签: ruby comparison operators


    【解决方案1】:

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

    class MyCustomClass
      include Comparable
    
      # ...
    
      def <=>(other)
        # e.g. compare self to fixnum and return -1, 0, 1
      end
    end
    

    【讨论】:

    • 适用于MyCustomClass.new &gt; 42,但似乎不适用于42 &gt; MyCustomClass.new。也许我做错了什么?
    猜你喜欢
    • 2019-07-03
    • 2021-06-12
    • 2017-02-07
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2018-07-12
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多