respond_to?
方法将要检查的方法作为参数,但作为符号。
为什么作为符号?而ruby又是如何将方法转化为符号的呢?
最佳答案
没有魔法。方法通过名称附加到对象,名称是一个符号。事实上,Math.sin(2)
基本上是 Math.send(:sin, 2)
的简写(“发送消息 :sin
到 Math
对象,参数为 2
")。您还可以访问方法本身:Math.method(:sin)
将为您提供关联的 Method
对象(其名称为 Math.method(:sin)。 name
,当然是 :sin
),Math.methods
会列出所有实现的方法的名称。 Math.respond_to?(:sin)
基本上可以重写为 Math.methods.include?(:sin)
(这是简化的,因为它忽略了 respond_to_missing?
,但是...对于本次讨论来说已经足够接近了)。
这样想。你去 friend 家,他们的妈妈来开门。你问,“你好,蒂姆在吗?”你不需要真的把你的 friend 拖到门口问“你好,这个人在吗?”这个名字也很管用。 :)
编辑:
Hmmm that's confusing right now for me. What does named mean exactly? I mean maybe with a little example. I call it with array.each. When does the "name" :each come into play then?
我不确定如何更好地解释它。方法有名字,就像人有名字一样。当您说 array.each
时,它会将消息 :each
发送到变量 array
中包含的对象,几乎就是array.send(:each)
就可以了。方法是通过名称附加到对象的代码片段:当对象收到消息时,它会运行与该消息关联的代码片段。
具体来说,在标准的 Ruby 实现中,Array
类的对象在收到消息 :each
时,将调用 C 函数 rb_ary_each
在 Ruby 源代码中定义,并使用 rb_define_method(rb_cArray, "each", rb_ary_each, 0)
链接到消息 :each
(也在 Ruby 源代码中)代码)。
在Ruby 内部,基本上有两种等效的方法来定义方法。这两个是等价的:
class Foo
def bar
puts "hello"
end
end
class Foo
define_method(:bar) do
puts "hello"
end
end
它们都做同样的事情:将消息 :bar
与代码段 do puts "hello"end
相关联。当 :bar
被 Foo
接收时(无论是通过 Foo.send(:bar)
还是通过 Foo.bar
), 运行这段代码。
关于ruby - Ruby 如何将方法转换为符号作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43864383/