“k.send:你好” -如果k是“接收者”,那么谁是发送者?
在下面的示例中,为什么我们说“k.send :hello”而不是“k.receive :hello”,如果
听起来 k 是发送者而不是接收者。
当我们说“k.send :hello”时,如果不是k,那么谁在发送?
(你是不是也和我一样困惑呢?)
class Klass
def hello
"Hello!"
end
end
k = Klass.new
k.send :hello #=> "Hello"
k.hello #=> "Hello"
In the example below, why do we say "k.send :hello" instead of "k.receive :hello" if, as stated elsewhere, k is actually the receiver?
It sounds like k is the sender rather than the receiver.
When we say "k.send :hello" who is sending, if not k?
(Are you as confused as I am?)
class Klass
def hello
"Hello!"
end
end
k = Klass.new
k.send :hello #=> "Hello"
k.hello #=> "Hello"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Smalltalk 中,一切都是对象。 “发送者”是消息起源范围的所有者的对象(即“this”或“self”指针)。
和以前一样,Ruby 继承了这个概念。 用不太抽象的术语来说,如果我给你寄一封信,我就是“发件人”(信件来自我的办公室),而你就是“收件人”(正面的地址是你的)。 所以我会写 foo.send myLetter:你,foo,收到我的信。 发送者是隐式的,是执行“发布”的代码的所有者。
In Smalltalk, everything is an object. The "sender" is the object who is the owner of the scope where the message originated (i.e. the "this" or "self" pointer).
As before, Ruby inherits this concept. In less abstract terms, if I post you a letter, I am the "sender" (it came from my office), and you are the "reciever" (the address on the front is yours). So I'd write foo.send myLetter: You, foo, receive my letter. The sender is implicit, the owner of the code doing the "posting".
任何包含此代码的对象都在发送消息——大概是 main。 让我们用更明确的对象和正常的消息传递来看看它。
在此代码的最后一行中,main 将
marry
发送给 patty,而 patty 又发送自己last_name=
并发送 boblast_name
。Whatever object contains this code is sending the message — presumably main. Let's look at it with more explicit objects and normal message-passing.
In the last line of this code, main is sending
marry
to patty, and patty in turn sends herselflast_name=
and sends boblast_name
.我知道你在哪里感到困惑,但问题很大程度上是语义上的。 您的论点是
send
方法实际上应该是receive
,因为k
正在接收一条消息(即 <代码>k.receive :hello)。 用简单的英语来说,您将k.send :hello
读作“k 发送消息 'hello'(给谁?)”,而不是“k 发送消息 'hello'”。可以将方法重命名为“receive”,但这也有点用词不当,因为
k
可能不会接收消息 -k
可能不会响应消息,k
可能会选择忽略它,或者k
可能会选择将其传递给另一个对象。 在 Ruby(以及影响 Ruby 的 Smalltalk)中,方法更像是做某事的请求,而不是命令。I can see where you're getting confused, but the issue is largely semantic. Your argument is that the
send
method should really bereceive
, sincek
is receiving a message (i.e.,k.receive :hello
). In plain English, you readk.send :hello
as "k sends the message 'hello' (to whom?)", rather than "k is sent the messsage 'hello'".One could rename the method "receive", but that's also a bit of a misnomer, because
k
might not receive the message --k
may not respond to the message,k
may choose to ignore it, ork
may choose to pass it on to another object. In Ruby (and Smalltalk, which influenced Ruby), methods are more like requests to do something, rather than commands to do it.