2013-02-24 38 views
13
def test 
    "Hello World" 
end 

p method(:test).call #"Hello World" 
p method("test").call #"Hello World" 

我的問題是:當我們將一個符號傳遞給call方法時會發生什麼?請問紅寶石將符號轉換爲一個字符串,然後執行它?如果是這樣,那麼它的目的是什麼?瞭解Ruby方法#call

如果不是,那麼究竟發生了什麼? 您能否詳細說明一下? 對不起,如果我不明確。

+0

不管它做什麼都是在C裏面用Ruby來完成的。它不應該緊。 – sawa 2013-02-24 07:34:59

回答

14

當你執行def test ...之外的任何明確的類或模塊定義的,你基本上是在Object類中的上下文,所以test現在是Object

irb實例方法...

1.8.7 :001 > def test 
1.8.7 :002?> "Hello world" 
1.8.7 :003?> end 
=> nil 
1.8.7 :004 > Object.instance_methods.sort 
=> ["==", "===", "=~", "__id__", "__send__", "class", "clone", "display", "dup", "enum_for", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "inspect", "instance_eval", "instance_exec", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "methods", "nil?", "object_id", "private_methods", "protected_methods", "public_methods", "respond_to?", "send", "singleton_methods", "taint", "tainted?", "tap", "test", "to_a", "to_enum", "to_s", "type", "untaint"] 

methodObject類的實例方法,它基本上由一切繼承。當你在任何明確的類或模塊定義之外調用method時,你基本上調用它作爲Object類的方法,並且該類本身是Class的一個實例,它是Object的一個子類(對不起 - 我知道這是一個有點混亂跟着)。

因此 - method方法接受一個字符串或一個符號,並在調用.method的同一對象上返回一個封裝該名稱的綁定方法的對象。在這種情況下,test方法綁定到Object對象。

method(:test).call表示調用test方法Object,這是您之前通過def test ...定義的方法。

+0

@MisterCal從irb控制檯,Object.class' => Class。 – 2017-11-03 21:56:10

+0

啊!刪除。我基於Object是Class的超類的事實做出了一個假設。我現在看到,有點混亂哈哈。 – MisterCal 2017-11-04 00:20:52