25

I'm reading a document that talks about a method having a receiver. What's a receiver?

lorz
  • 1,129
  • 1
  • 11
  • 14

3 Answers3

26

In Ruby (and other languages that take inspiration from SmallTalk) objects are thought of as sending and receiving 'messages'.

In Ruby, Object, the base class of everything, has a send method: Object.send For example:

class Klass
  def hello
    "Hello!"
  end
end
k = Klass.new
k.send :hello     #=> "Hello!"
k.hello           #=> "Hello!"

In both of these cases k is the receiver of the 'hello' message.

tamerlaha
  • 1,902
  • 1
  • 17
  • 25
Cameron Pope
  • 7,565
  • 2
  • 26
  • 24
  • 1
    Is "k.send :hello" actually a syntactically valid way of calling "k.hello" in Ruby? – lorz May 27 '09 at 16:11
  • 3
    You say k is the receiver. So why do we say "k.send :hello" instead of "k.receive :hello"? It *sounds* like k is the sender rather than the receiver. – lorz May 27 '09 at 16:17
  • 2
    Because you're sending TO k, and not receiving TO k. That latter option makes little sense. ;) – Robert K May 27 '09 at 16:25
  • I am wondering since in Ruby every thing is an object and every function is some method. But in terms of class method `class Hello; def self.say; puts "hello"; end; end` what is the receiver when you call `Hello.say`? Is `Hello` also an object? – Lin Aug 24 '16 at 19:25
  • Yes. `Hello` is truly an object. If you do `Hello.class`, then `Class` will be returned. Thus `Hello` is actually an instance of `Class` class. – Lin Aug 24 '16 at 20:24
8

In the original Smalltalk terminology, methods on "objects" were instead refered to as messages to objects (i.e. you didn't call a method on object foo, you sent object foo a message). So foo.blah is sending the "blah" message, which the "foo" object is receiving; "foo" is the receiver of "blah".

Adam Wright
  • 48,938
  • 12
  • 131
  • 152
7

the object before the .

think of calling a method x.y as saying "send instruction y to object x".

it's the smalltalk way of thinking, it will serve you well as you get to some of Ruby's more advanced features.

chillitom
  • 24,888
  • 17
  • 83
  • 118