“k.send :hello” - if k is the “receiver”, who is the sender?

强颜欢笑 提交于 2019-12-10 03:38:54

问题


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"

回答1:


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

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.




回答2:


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".




回答3:


I can see where you're getting confused, but the issue is largely semantic. Your argument is that the send method should really be receive, since k is receiving a message (i.e., k.receive :hello). In plain English, you read k.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, or k 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.



来源:https://stackoverflow.com/questions/916795/k-send-hello-if-k-is-the-receiver-who-is-the-sender

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!