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?
super
in Ruby doesn't work like that.super
calls the superclasses implementation of this method. So: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:Only use explicit
super
arguments if you need to change the arguments given to the superclass implementation.