“k.send:你好"- 如果 k 是“接收者",那么谁是发送者? [英] "k.send :hello" - if k is the "receiver", who is the sender?
问题描述
在下面的例子中,为什么我们说k.send :hello"而不是k.receive :hello"如果,如别处所述,k实际上是接收者?
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?
它听起来就像 k 是发送者而不是接收者.
It sounds like k is the sender rather than the receiver.
当我们说k.send :hello"时,谁在发送,如果不是 k?
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"
推荐答案
任何包含此代码的对象都在发送消息——大概是主要的.让我们用更明确的对象和正常的消息传递来看看它.
Whatever object contains this code is sending the message — presumably main. Let's look at it with more explicit objects and normal message-passing.
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name, @last_name = first_name, last_name
end
def marry(other)
self.last_name = other.last_name
end
end
bob = Person.new('Bob', 'Smith')
patty = Person.new('Patricia', 'Johnson')
patty.marry bob
在这段代码的最后一行,main 发送 marry
给 patty,patty 依次发送自己 last_name=
并发送 bob last_name
.
In the last line of this code, main is sending marry
to patty, and patty in turn sends herself last_name=
and sends bob last_name
.
这篇关于“k.send:你好"- 如果 k 是“接收者",那么谁是发送者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!