Instance Methods, Singleton Methods, Class Methods, and the Eigenclass, in Ruby
Instance Methods are methods that are available to all instances of the class. For example:
Singleton Methods are methods that are available only to a specific instance of a class. For example:
Class Methods
First of all, let’s cover Class Variables.
Class Variables eg @@name are available to all instances of that class. For example:
When using an Instance Variable, the same is not true:
Class Methods are methods that are only available to the class itself.
In our Ruby apps, we often want to do something like Square.sides and have it return a value. Because class variables are available to all instances of that class (and therefore all classes that inherit from it), it can cause difficult debugging and ‘ghost’ issues in large codebases. It is therefore generally preferred that they are not used (this is also why Rubocop doesn’t allow Class Variables).
Another way to achieve the ability to be able to do Square.sides and have it return a value, without it referencing a Class Variable, is to use a Class Method that returns an Instance Variable.
So, in both cases:
Class methods are placed in the Eigenclass which is an anonymous class that Ruby places in the hierarchy chain, so as not to affect instances of that class.
You may never do the following, but it drives home the above; lets create a Square class containing Instance Methods and Class Methods:
square_instance is an instance of Square, whereas Square is an instance of Class; the Eigenclass holds Square’s class methods its variable @sides. Well, that’s the way I think about it anyway! (Need to dig into this and understand it a bit more).
If we reload this code and do it the other way round, the same sort of thing occurs: