Ruby 发送与 __send__ [英] Ruby send vs __send__
问题描述
我理解 some_instance.send
的概念,但我想弄清楚为什么你可以同时调用它.Ruby Koans 暗示除了提供许多不同的方法来做同样的事情之外,还有一些原因.以下是两个用法示例:
I understand the concept of some_instance.send
but I'm trying to figure out why you can call this both ways. The Ruby Koans imply that there is some reason beyond providing lots of different ways to do the same thing. Here are the two examples of usage:
class Foo
def bar?
true
end
end
foo = Foo.new
foo.send(:bar?)
foo.__send__(:bar?)
有人对此有任何想法吗?
Anyone have any idea about this?
推荐答案
某些类(例如标准库的套接字类)定义了自己的 send
方法,该方法与 Object 无关#发送
.所以如果你想处理任何类的对象,你需要使用 __send__
以确保安全.
Some classes (for example the standard library's socket class) define their own send
method which has nothing to do with Object#send
. So if you want to work with objects of any class, you need to use __send__
to be on the safe side.
现在剩下的问题是,为什么有 send
而不仅仅是 __send__
.如果只有 __send__
名称 send
可以被其他类使用而不会产生任何混淆.原因是 send
首先存在,直到后来才意识到名称 send
也可能在其他上下文中有用,所以 __send__
已添加(顺便说一下,这与 id
和 object_id
发生的事情相同).
Now that leaves the question, why there is send
and not just __send__
. If there were only __send__
the name send
could be used by other classes without any confusion. The reason for that is that send
existed first and only later it was realized that the name send
might also usefully be used in other contexts, so __send__
was added (that's the same thing that happened with id
and object_id
by the way).
这篇关于Ruby 发送与 __send__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!