2012-03-06 13 views
2

假設我有全局法hello(name)和實例方法hello這樣的:如何從全局範圍調用與ruby中的實例方法同名的方法?

def hello(name) 
    puts("Hello " + name) 
end 

class String 
    def hello 
    hello(self)   # does not work, see below 
    end 
end 

我希望能夠說

"world".hello() 

但紅寶石不會讓我。它抱怨

in `hello': wrong number of arguments (1 for 0) (ArgumentError) 

我錯過了什麼?

+1

您的方法'hello'被方法'String#hello'遮蔽。參見[如何在ruby中訪問一個(被遮蔽的)全局函數](http://stackoverflow.com/questions/2681895/how-to-access-a-shadowed-global-function-in-ruby)來解釋如何叫它。 – gregor 2012-03-06 23:33:18

回答

6

這應該工作

class String 
    def hello 
    Kernel.send(:hello,self) 
    end 
end 
+0

謝謝! d (^_^) b – Tobias 2012-03-06 23:43:37

1

Object.send(:hello,self)也適用。

相關問題