加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

了解Ruby方法#call

发布时间:2020-12-16 23:04:07 所属栏目:百科 来源:网络整理
导读:def test "Hello World"endp method(:test).call #"Hello World"p method("test").call #"Hello World" 我的问题是:当我们传递符号到调用方法时会发生什么?将ruby将符号转换为String,然后执行它吗?那么,那是什么目的呢? 如果没有,那么实际发生了什么呢?
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 ….

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读