Who am I? Man’s age old question is the same one I’ve been asking myself in Ruby over the last few days. The key word self is the embodiment of the question, with a slight twist. In Ruby, everything is an object, and there is one and only one current object at a given point. This current object is self. Depending on where you are in the program, self will be different. Here are some examples to illustrate how self changes depending on the context of the situation.
Context 1: Top-Level
Main is the default top level object that self refers to, and main itself is an instance of an object. Self in top level methods reference whatever object the method is being called on.
Context 2: Classes/Modules
Here, self is the Class or Module object.
So, we’ve seen self go from top-level main to individual Classes and Modules.
Context 3: Instance and Class Methods
The key here is that a method is telling an object what to do, so self within a method is always the object on which the method is being called on (the receiver of the message). When we first created the instance of the Class Rapper (ice_cube = Rapper.new), and subsequently called time_period on that instance, self is referencing that specific instance, and denotes it by the #Rapper:0x bunch of digits, which is the memory location of that instance. We see that when we call the consensus method on that instance, we get the same object (self) confirmed by the same reference number. However, if we look at the class method self.consensus, the object in self is the class Rapper. Of note, defining the method as self.consensus would have been equivalent to writing Rapper.consensus, which underscores that Rapper = self. In summary, self can be representing the Class object or an instance of the Class object depending on the context.
And last but not least, here’s Ice Cube’s words of wisdom on the subject…