I wanted to write down a little bit about my understanding of how methods work inside of classes and how to know if you want your method to be ‘self.method’ or just ‘method.’
Take the following situation…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
So we have the class Dog with a few attributes, and we’ve created two dogs. Now we’re going to create two methods, one to make an individual dog bark and one to make the Dog class bark.
1 2 3 4 5 6 7 8 9 10 11
Now, if we put fido.barkley we will see “I AM TOTALLY BARKING YOU GUYS”
If you put fido.bark though, you will get a NoMethodError, because the bark method is defined for the class it was in because we defined it as self.bark, with self referring to the current object its contained within.
So… If we put Dog.bark we will see “THE CONCEPT OF A DOG IS BARKING, RUN FOR YOUR LIVES!”
Similarly, if we were to call Dog.barkley we would again get a NoMethodError because the method is defined without the self demarcation, telling ruby that it is to be used by individual dogs, not by the class as a whole.
So bringing things back around, if you want your overall class to respond to a method, name it as self.method, if you want a specific instance of that class to respond to it, do not have the self in there.