user1934428 user1934428 -4 years ago 91
Ruby Question

How to implement 'Comparable' if parent class already has a '=='

I have a library class, which provides methods for equality and inequality. I'm deriving another class from this, which, differently from the parent class, introduces an ordering relation, i.e. it would make sense to ask for two elements of the derived class, which one is smaller. In particular, arrays of objects of the derived class can be sorted.

My first approach was

class MyClass < LibraryClass
def <(other)
...
end
def <=>(other)
return 0 if self == other
return -1 if self < other
return 1
end
# code for operators > <= >= is not shown here....
end


This seems to work, but I thought that it may be better to instead [sic]
Comparable
, since this would give plenty of other methods for free.


  1. The description of
    Comparable
    says that I have to implement the
    <=>
    operator, and other operators including
    ==
    and
    !=
    would then be automatically implemented. However, I am already happy with the
    ==
    operator from the parent class, so no new method for equality should be generated.

  2. I want to test for equality using the
    ==
    operator from the parent class. If I implement the
    <=>
    operator, and
    Comparable
    implements an
    ==
    operator in terms of my
    <=>
    operator, I would end up in a recursive call.



For expression
self == other
, how can I specify that the
==
operator of the parent class should be invoked?

Answer Source

The include makes Comparable the superclass of MyClass and LibraryClass the superclass of Comparable. So, the implementation of == in Comparable overrides the implementation of == in LibraryClass.

What you can then do, is to override == again in MyClass with a version that is identical to the one in LibraryClass:

class MyClass < LibraryClass
  include Comparable

  def <=>(other)
    # whatever
  end

  define_method(:==, LibraryClass.public_instance_method(:==))
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download