了解Ruby方法#call

前端之家收集整理的这篇文章主要介绍了了解Ruby方法#call前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
def test
  "Hello World"
end

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

我的问题是:当我们传递符号到调用方法时会发生什么?将ruby将符号转换为String,然后执行它吗?那么,那是什么目的呢?

如果没有,那么实际发生了什么呢?
请你详细说明一下
对不起,如果我不清楚自己.

解决方法

当您在任何明确的类或模块定义之外执行def test …时,您基本上处于Object类上下文中,因此测试现在是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"]

方法是Object类的一个实例方法,它基本上是所有的东西.当您调用任何显式类或模块定义之外的方法时,您本质上将其作为Object类的方法调用,该类本身就是Class的一个实例,它是Object的一个子类(对不起 – 我知道这是一个有点混乱).

所以 – 方法方法接受一个字符串或一个符号,并返回一个对象,该对象将该名称的绑定方法封装在调用了.method的同一个对象上.在这种情况下,这是绑定到Object对象的测试方法.

方法(:test).call意味着调用Object的测试方法,这是通过def test ….

猜你在找的Ruby相关文章