Bird
Raised Fist0
RubyConceptBeginner · 3 min read

What Is a Class Method in Ruby: Simple Explanation and Example

A class method in Ruby is a method that belongs to the class itself, not to instances of the class. You call it directly on the class, using self.method_name inside the class definition or by prefixing the method name with the class name.
⚙️

How It Works

Think of a Ruby class like a blueprint for making objects. Normally, methods inside the class are like instructions for each object made from that blueprint. But a class method is different—it belongs to the blueprint itself, not the objects.

This means you can call a class method without creating an object first. Inside the class, you define a class method by putting self. before the method name. This tells Ruby, "This method is for the class, not for individual objects." It's like having a special tool that only the blueprint can use, not the things made from it.

💻

Example

This example shows a class method that returns the name of the class. Notice how we use self.class_name to define it, and then call it directly on the class.

ruby
class Car
  def self.class_name
    "Car"
  end
end

puts Car.class_name
Output
Car
🎯

When to Use

Use class methods when you want to perform actions related to the class as a whole, not to any single object. For example, you might use a class method to create new objects in a special way, keep track of how many objects were made, or provide information about the class itself.

In real life, imagine a factory blueprint that can tell you how many products it has made so far. You don’t need to look at each product; you just ask the blueprint. That’s what class methods do in Ruby.

✅

Key Points

  • Class methods belong to the class, not instances.
  • Defined with self.method_name inside the class.
  • Called directly on the class, like ClassName.method_name.
  • Useful for actions related to the class itself, like counting instances or factory methods.
✅

Key Takeaways

Class methods are called on the class itself, not on objects.
Define class methods using self.method_name inside the class.
Use class methods for tasks related to the class as a whole.
Class methods help organize code that doesn’t belong to individual objects.