17
def test
  "Hello World"
end

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

我的问题是:当我们将符号传递给call方法时会发生什么?ruby 会将符号转换为字符串然后执行吗?如果是这样,那么它的目的是什么?

如果不是,那么实际上会发生什么?你能详细说明一下吗?对不起,如果我没有让自己清楚。

4

1 回答 1

15

当您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 ....

于 2013-02-24T04:56:00.637 回答