I decided to get up close and personal with self this week. Mainly because it’s an abstract concept that will surely deceive me in the future, IF I don’t attempt to hold on tight to it now. So bear with me as I try my best to decipher the ever-morphing state of the one and only, self.
The fine, nitty-gritty definition of the self method is pretty straightforward, self refers to the object it belongs to. Meaning, whatever part of your program you are in, that is the reference of which the self method will be called upon. The self method can be called on the instance of the class or on the instance of the object of the class, but don’t forget that a class is also an object. But of course you know that, and if you’re not quite aware of this, let me be the first to warn you of Ruby’s sneaky ways. Ruby will try to cloud your judgement and make you think that certain methods, variables, strings or even integers are not objects, but do not be fooled my friends, Ruby is a Objected Oriented language after all, and to Ruby all is an object. Fun, right?! Stay with me here, I promise I’ll try to make this fun.
My biggest hurdle in understanding the full scope of the self method, is knowing what object I am utilizing the self method on, and what to keep in mind before pulling the trigger on this sneaky method. To try to really bring this home, I scoured the internet in search of some closure. So can you always tell which object “self” actually represents? Simple, by keeping in mind “self” protocol, or the golden rules.Brought to you by hackhands, they put this simply as:
The Golden Three Rules of Self
These set of rules have been really helpful in grasping self (ha!no pun intended here). The article goes on to explain further, you can read the entire post here. To put it into my own words I baked up a simple example below, see I told you this would get fun!
In the example above you have a clear idea of the difference between the class and instance method. The class method here is chocolate, so when I call chocolate on the Cake class Ruby will happily oblige. But as you can see by the first error message Ruby will not oblige if I call strawberry on the Cake class because, strawberry is an instance method and thus will never work. The other few lines, I am simply calling both methods on an instance of the Cake class, with Cake.new.