Ruby Definition of Self

rubyself

I was reading a Ruby book and came across this definition of the pseudo-variable self:

self – receiver object of the current
method

Could someone break down that definition and explain what it means? I don't understand any of it.

EDIT: I actually have a pretty good idea of what self is (and its applications) and I know how to search on Google. I was just wondering if someone could explain the definition I quoted. That specifically.

Best Solution

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