我正在尝试一个类的比较器而不重写超类的比较逻辑,但由于某种原因,我无法从超类比较器获取返回值。可以使用以下代码段演示此问题:
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
我得到以下输出:
Calling A's comparator
The return value from calling the A's comparator is of type NilClass
我究竟做错了什么?