One of the most important aspects of writing the ruby classes is to understand the difference between the class methods and the instance methods & we’d like to cover this difference in this post of ours. First off, the method that resides at the class level is said to be the class method and the one that resides at an object level, is said to be the instance method. To make it easier to relate with – for the developers, the methods that are called on a class are the class methods and the ones that are called on an instance of a class, are the instance methods.
When working on Ruby, you must know that classes are objects too and therefore, the methods that are defined as the class methods correspond specifically only to the objects that define those classes.
For example, if we define my_class_method in a class called as Test, my_class_method will only correspond to the object called Test, and this Test is nothing but an example of a built-in ruby class called as ‘Class’.
When to use a class method?
A class method is a piece of functionality independent of any particular instance, rather, it is the one that just belongs to a class. The class method is used for the functionality that is not specific to any instance of a class.
When to use the Instance Methods?
Instance methods are used when you are required to act on a specific instance of a class. When you need to introduce a functionality that corresponds to the identity of an instance, you should use the instance method.
It is important to understand this seemingly subtle difference between where to use a class method and where to employ an instance method because in absence of a clear understanding on this, your object-oriented design can go wrong. So, this leads you to often encounter cases where both class methods and instance methods have been wrongly used in place of each other. The encapsulation and modelling attributes of the object-oriented design are the key elements of its success. So, it should be kept in mind that when the functionality to be implemented corresponds to an object, the instance methods need to be employed. At the same time, it is also important to know whether the functionality that’s being implemented is in line with the specific instance of the object or not.