我想爲一個類的比較器而不重寫來自超類的比較邏輯,但出於某種原因,我無法從超類比較器中獲取返回值。這個問題可以用下面的代碼片段來說明:如何在Ruby中調用超類比較器(飛船)方法?
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
我在做什麼錯?
當你調用'super'時會自動提供參數,不需要指定其他參數。 – mechanicalfish
是真的。 :) – BroiSatse