Class methods
Learn what class methods are and how to use them in Ruby.
We'll cover the following...
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, and it turned out that the author was not Sam Smith, but Pat King. We would probably get an eraser and replace the wrong name with the right one.
For 1,000 already produced objects, nothing will change since it’s meta-information. It’s not the size of an object. It can exist without this information. However, if somebody will ask who is the actual author of this wonderful item, the answer will be different.
So, this meta-information is like ...