Ruby and other languages (such as Smalltalk and Objective-C) prefer the term “message passing”, whereas Java and C++ prefer “method invocation”. That is, the “Java way” is to call a method on an object — running code in the context of an object — whereas the “Ruby way” is to send an object a message, to which the object responds by running its method.
Ruby would describe the line my_string.length
as “sending my_string
the length
message”. The my_string
receives the message, and so is called the receiver; inside the definition of the length
method, self
would refer to my_string
. You can get the same effect with my_string.send(:length)
.
Thinking of this concept in terms of message passing is more flexible than thinking in terms of method invocation. To invoke a method on an object, that method must have been pre-defined, whereas you can send an object a message that it can choose to handle dynamically (with respond_to?
and method_missing
). This flexibility is one aspect that allows Ruby to be used as concise domain-specific languages (DSL).