簡體   English   中英

理解Ruby方法#call

[英]Understanding the Ruby method #call

def test
  "Hello World"
end

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

我的問題是:當我們將符號傳遞給call方法時會發生什么? ruby會將符號轉換為String然后執行嗎? 如果是這樣,那么它的目的是什么?

如果沒有,那么實際發生了什么? 你能詳細說明嗎? 對不起,如果我沒有說清楚。

當您在任何顯式類或模塊定義之外執行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的同一對象上。 在這種情況下,這是綁定到Object對象的test方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM