Me, My”self” and I
The concept of self in Ruby is not a particularly easy concept to grasp but that does not mean it is impossible. The simplest case would be the “self” word being used within a class.
When “self” is defined WITH the method definition, as in the case of #self.all, that “self” is referring to the class Book. To think about it, at that point we are not IN the method yet, so that “self” has to be referring to the class.
On the other hand when we define #save we have “self” INSIDE the method definition. In this case “self” would be referring to the instance that it is being called on.
“harry_potter” is declared as an instance of the Book class with its own location within memory and its own attributes. Calling #save on “harry_potter” will trigger the code ALL_BOOKS << self that was defined earlier.
“harry_potter” is the receiver and #save is the method.
The “self” in the #save method is referencing the object that #save is being called on, so in this case it would be the “harry_potter” instance.
Next discussion will be the concept of implicit and explicit “self”.