2013-02-24 40 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