我想將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
。
是的,你是絕對的權利。謝謝。被「Kernel」的默默無聞分心了。 – Peter 2010-05-25 01:17:49