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 ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.