This is an attempt on consolidating my thoughts on Ruby’s self, taken from Well Grounded Rubyist chapter 5.
Another crucial point of Ruby to understand is the notion of self. Self is used to refer to the current object or the default object at a given time. At every point of your program there is one and only self.
Self inside Class and Module is straight forward. Self in method is also not too hard to understand, but you need to understand the context of the method.
Method can belong to class, self in method class will return the class object itself (remember that class IS object in Ruby). Method can belong to an instance of a class, self in that context will surprise2 return the instance. Method can be a singleton - in this case, calling self will also return the instance of a class.
Another point about self is: it is the default receiver of messages (see the code snippet below - it is explained there).
Below is code snippet that I hope illustrate the points above (stitched together from the examples in the book):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
And here is the output:
1 2 3 4 5 6 7 8 9 | |