Class methods

Learn what class methods are and how to use them in Ruby.

What are class methods

We are already familiar with instance methods. However, there is another type of method called class methods. Some other programming languages refer to them as static methods or self methods. The same thing is true for variables: there are instance and class variables, though class variables are used less often. There are also local variables, which are only available inside methods. We need to understand the difference between instance and class methods (and variables, of course).

Imagine a technical drawing of an object, or see an example in the “Classes and Objects” chapter. This drawing has all sizes specified. The drawing, or class, can be used to produce an actual object, or instance. Sizes from the drawing make sense only when an object has been produced. When there is no object, sizes are just numbers on paper. The technical drawing says, “When an actual object (instance, in this case) is going to be produced, the size should be these values.” That’s why we call them instance variables.

However, there is also meta-information in the drawing, like who the author is. Imagine we’ve produced one thousand objects, or instances, ...