In Ruby, class methods are defined on the class itself, while instance methods are defined on instances of the class. Class methods are used when you want to perform an action on the class itself, rather than on individual instances of the class.
Here's an example where a class method is used and necessary:
main.rb153 chars10 lines
In this example, the square
method is a class method defined using the self
keyword. The square
method calculates the square of a given number.
Using the class method, we can directly call MathUtils.square(5)
without creating an instance of the MathUtils
class. This is useful when you want to perform a calculation or operation that is related to the class itself and does not depend on the specific properties of instances.
If we were using instance methods instead, we would need to create an instance of MathUtils
first, and then call the square
method on that instance. However, since the square
method does not rely on any specific instance variables or state, using an instance method would be unnecessary in this case.
In summary, class methods are used when you want to perform actions on the class itself, without relying on the state of individual instances.
gistlibby LogSnag