def test
"Hello World"
end
p method(:test).call #"Hello World"
p method("test").call #"Hello World"
我的问题是:当我们将符号传递给
call
方法时会发生什么?Ruby会将符号转换为字符串,然后执行它吗?如果是这样的话,那它的目的是什么?如果不是这样的话,那么实际上会发生什么?能否详细说明一下?如果我没有表述清楚,很抱歉。
def test
"Hello World"
end
p method(:test).call #"Hello World"
p method("test").call #"Hello World"
call
方法时会发生什么?Ruby会将符号转换为字符串,然后执行它吗?如果是这样的话,那它的目的是什么?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"]
method
是 Object
类的一个实例方法,被几乎所有对象继承。当你在任何明确的类或模块定义之外调用 method
时,实际上是将其作为 Object
类的一个方法调用,而该类本身是 Class
的一个实例,后者是 Object
的子类(抱歉——我知道这有点难以理解)。
因此,method
方法接受一个字符串或符号,并返回一个封装了同一对象上该名称绑定方法的对象。在这种情况下,这是绑定到 Object
对象的 test
方法。
method(:test).call
意味着调用 Object
的 test
方法,这是通过之前的 def test ...
定义的。
Object.class
=> Class。 - Steve Jorgensen