2010-05-25 27 views
2

我想將foo方法添加到Ruby的內核模塊中,所以我可以在任何地方寫foo(obj)並讓它對obj做些什麼。有時我想一個類重寫foo,所以我這樣做:強制要求在Ruby中調用Kernel :: method_name

module Kernel 
    private # important; this is what Ruby does for commands like 'puts', etc. 
    def foo x 
    if x.respond_to? :foo 
     x.foo # use overwritten method. 
    else 
     # do something to x. 
    end 
    end 
end 

這是很好的,和作品。但是,如果我想在其他某個覆蓋foo的對象中使用默認的Kernel::foo,該怎麼辦?由於我有一個實例方法foo,因此我失去了原始綁定到Kernel::foo

class Bar 
    def foo # override behaviour of Kernel::foo for Bar objects. 
    foo(3) # calls Bar::foo, not the desired call of Kernel::foo. 
    Kernel::foo(3) # can't call Kernel::foo because it's private. 
    # question: how do I call Kernel::foo on 3? 
    end 
end 

有沒有乾淨的方式來解決這個問題?我寧願沒有兩個不同的名字,我絕對不想公開讓Kernel::foo

回答

3

您可以使用super關鍵字從重寫的方法調用超類的實現。

class Bar 
    def foo # override behaviour of Kernel::foo for Bar objects. 
    super 
    # do something else here 
    end 
end 
+0

是的,你是絕對的權利。謝謝。被「Kernel」的默默無聞分心了。 – Peter 2010-05-25 01:17:49

0

只需使用aliasalias_method之前重新定義Kernel.foo保持原來的版本的參考。

+0

我已經試過這個,它不起作用,因爲'Kernel :: foo'在代碼定義點沒有混入。 – Peter 2010-05-25 01:20:17

+0

啊,明白了。是的,這種方式在你的情況下不起作用。 – x1a4 2010-05-25 01:23:50

+0

這也會污染你的名字空間。 – rampion 2010-05-25 17:33:07