2014-01-13 27 views
0

我想爲一個類的比較器而不重寫來自超類的比較邏輯,但出於某種原因,我無法從超類比較器中獲取返回值。這個問題可以用下面的代碼片段來說明:如何在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 

我在做什麼錯?

回答

3

super在Ruby沒有這樣的工作。 super調用超類實現這個方法。所以:

c = super(other) 

您還沒有提供明確的說法,因爲super不帶參數只是調用具有相同參數的超類方法的子類實現復興:

c = super 

只有使用顯式super參數,如果您需要更改提供給超類實現的參數。

0

super是基本方法,你不需要調用<=>它:

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 
+0

當你調用'super'時會自動提供參數,不需要指定其他參數。 – mechanicalfish

+0

是真的。 :) – BroiSatse