The purpose of a class method is to perform an action without the need to instantiate an object of that class. A very good example that you already know is .new, when you create an instance of a class you are calling a class method.

Let’s see the most common ways to define a class method:

  • Singleton method:
class Game
  def self.leaderboard
    'points of all players'
  end
end
  • Singleton class:
class Game
  class << self
    def leaderboard
      'points of all players'
    end
  end  
end

In the singleton class you can see that leaderboard is an instance method of the Game singleton class. This means that under the hood every method in Ruby is an instance method.

When should you use a class method?

I see two cases that fit very well for this:

  • When you want to instantiate or initialize something. For example, when you try to make a request: Net::HTTP.get_response(URI('https://www.diazweb.net')) it initializes the request, execute and returns the response.

  • When an action is common or global to all instances. In our example, we used the leaderboard method that calculates the points of all players (each player has an instance).