m_x
m_x

Reputation: 12554

How to allow comparison between Fixnum and custom class?

I've already used coercion to handle arithmetic operators :

class MyCustomClass

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

end

Which means I can do:

42 + MyCustomClass.new

I'd like to know if a similar mechanism exists that would allow me to perform comparisons (without monkey patching Fixnum) :

42 > MyCustomClass.new

Upvotes: 0

Views: 84

Answers (1)

Stefan
Stefan

Reputation: 114158

You just have to include Comparable and define the <=> operator:

class MyCustomClass
  include Comparable

  # ...

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

Upvotes: 1

Related Questions