Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 619
lorz Avatar asked May 27 '09 16:05

lorz


2 Answers

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

like image 153
Adam Wright Avatar answered Sep 27 '22 19:09

Adam Wright


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.

like image 40
Chuck Avatar answered Sep 27 '22 19:09

Chuck