I'm reading a document that talks about a method having a receiver. What's a receiver?
-
1I used to wonder if it was a term inspired by American football. – Andrew Grimm Mar 31 '10 at 06:57
-
The new idea I got from ruby is that OO programming is like a kind of message passing. – Alex Jun 15 '12 at 08:13
3 Answers
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.

- 1,902
- 1
- 17
- 25

- 7,565
- 2
- 26
- 24
-
1Is "k.send :hello" actually a syntactically valid way of calling "k.hello" in Ruby? – lorz May 27 '09 at 16:11
-
3You 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
-
2Because 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
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".

- 48,938
- 12
- 131
- 152
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.

- 24,888
- 17
- 83
- 118