0
0
Rubyprogramming~5 mins

Class methods with self prefix in Ruby

Choose your learning style9 modes available
Introduction

Class methods let you call a function directly on the class, not on an object. Using self before a method name means the method belongs to the class itself.

When you want to create a method that works for the whole class, not just one object.
When you need a helper function that doesn't need to access instance data.
When you want to keep track of information shared by all objects of the class.
When you want to create factory methods that create new objects in a special way.
Syntax
Ruby
class ClassName
  def self.method_name
    # code here
  end
end

The self before the method name means this method belongs to the class.

You call class methods using the class name, like ClassName.method_name.

Examples
This defines a class method add that adds two numbers.
Ruby
class Calculator
  def self.add(a, b)
    a + b
  end
end
Calling the class method add on Calculator directly.
Ruby
puts Calculator.add(5, 3)  # Output: 8
This class method returns a string describing the species for all Person objects.
Ruby
class Person
  def self.species
    "Homo sapiens"
  end
end
Sample Program

This program defines a class method bark on the Dog class. It prints the sound a dog makes by calling the method on the class itself.

Ruby
class Dog
  def self.bark
    "Woof!"
  end
end

puts Dog.bark
OutputSuccess
Important Notes

Class methods cannot access instance variables because they belong to the class, not to any object.

You can also define class methods using class << self block for multiple methods.

Summary

Use self before a method name to make it a class method.

Class methods are called on the class, not on instances.

They are useful for shared behavior or utility functions related to the class.