What Are Class Methods For?
But why, you may reasonably ask, would you ever want to create a class method rather than the more usual instance method? There are two main reasons: First, a class method can be used as a “ready-to-run function” without having to go to the bother of creating an object just to use it, and second, it can be used on those occasions when you need to run a method before an object has been created.
For a few examples of using methods as “ready-to-run functions,” consider Ruby’s File class. Many of its methods are class methods. This is because most of the time you will be using them to do something to, or return information about, an existing file. You don’t need to create a new File object to do that; instead, you pass the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access