Question

I'm trying to a comparator for a class without rewriting the comparison logic from the superclass, but for some reason I cannot get the return value from the superclass comparator. This issue can be demonstrated with the following snippet:

class A
  def <=>(other)
    puts "Calling A's comparator"
    return 1
  end
end

class B < A
  attr_accessor :foo

  def initialize(foo)
    @foo = foo
  end

  def <=>(other)
    if self.foo == other.foo
      c = super.<=>(other)
      puts "The return value from calling the superclass comparator is of type #{c.class}"
    else
      self.foo <=> other.foo
    end
  end
end

b1 = B.new(1)
b2 = B.new(1)
b1 <=> b2

And I get the following output:

Calling A's comparator
The return value from calling the A's comparator is of type NilClass

What am I doing wrong?

Was it helpful?

Solution

super in Ruby doesn't work like that. super calls the superclasses implementation of this method. So:

c = super(other)

You also don't have to provide the explicit argument, as super with no arguments just calls the superclass method with the same arguments as the subclass implementation revived:

c = super

Only use explicit super arguments if you need to change the arguments given to the superclass implementation.

OTHER TIPS

super is a base method, you don't need to call <=> on it:

def <=>(other)
  if self.foo == other.foo
    c = super
    puts "The return value from calling the superclass comparator is of type #{c.class}"
  else
    self.foo <=> other.foo
  end
end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top