I'm reading a document that talks about a method having a receiver. What's a receiver?
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.
-
1Is "k.send :hello" actually a syntactically valid way of calling "k.hello" in Ruby?– lorzMay 27, 2009 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.– lorzMay 27, 2009 at 16:17
-
1Because you're sending TO k, and not receiving TO k. That latter option makes little sense. ;)– Robert KMay 27, 2009 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 callHello.say
? IsHello
also an object?– LinAug 24, 2016 at 19:25 -
Yes.
Hello
is truly an object. If you doHello.class
, thenClass
will be returned. ThusHello
is actually an instance ofClass
class.– LinAug 24, 2016 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".
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.