Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Definition of Self

Tags:

ruby

self

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.

like image 948
Devoted Avatar asked May 17 '09 04:05

Devoted


1 Answers

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

like image 123
jmah Avatar answered Oct 17 '22 22:10

jmah