Bird
Raised Fist0
Rubyprogramming~5 mins

Class methods with self prefix in Ruby

Choose your learning style10 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.

Practice

(1/5)
1. What does adding self. before a method name inside a Ruby class do?
easy
A. Defines a method that can only be called inside other methods
B. Makes the method private and inaccessible outside the class
C. Makes the method an instance method, callable on objects
D. Makes the method a class method, callable on the class itself

Solution

  1. Step 1: Understand the role of self. in method definition

    In Ruby, prefixing a method name with self. inside a class defines it as a class method.
  2. Step 2: Identify how class methods are called

    Class methods are called on the class itself, not on instances of the class.
  3. Final Answer:

    Makes the method a class method, callable on the class itself -> Option D
  4. Quick Check:

    self.method_name defines class method [OK]
Hint: Remember: self.method means class method, no instance needed [OK]
Common Mistakes:
  • Thinking self. makes method private
  • Confusing class methods with instance methods
  • Assuming self. methods are only for internal use
2. Which of the following is the correct syntax to define a class method named greet inside a Ruby class?
easy
A. def @greet; puts 'Hello'; end
B. def greet; puts 'Hello'; end
C. def self.greet; puts 'Hello'; end
D. def ::greet; puts 'Hello'; end

Solution

  1. Step 1: Recall class method syntax

    Class methods in Ruby are defined by prefixing the method name with self. inside the class.
  2. Step 2: Check each option

    def self.greet; puts 'Hello'; end uses def self.greet, which is the correct syntax for a class method.
  3. Final Answer:

    def self.greet; puts 'Hello'; end -> Option C
  4. Quick Check:

    Class method syntax = def self.method_name [OK]
Hint: Class methods always start with def self.method_name [OK]
Common Mistakes:
  • Omitting self. for class methods
  • Using instance variable syntax (@) for methods
  • Trying to use :: inside method definition
3. What will be the output of the following Ruby code?
class Calculator
  def self.add(a, b)
    a + b
  end
end

puts Calculator.add(3, 4)
medium
A. 7
B. 34
C. Error: undefined method 'add'
D. nil

Solution

  1. Step 1: Identify the method type and call

    The method add is defined as a class method using self.add, so it can be called on the class Calculator.
  2. Step 2: Evaluate the method call

    Calling Calculator.add(3, 4) returns the sum of 3 and 4, which is 7.
  3. Final Answer:

    7 -> Option A
  4. Quick Check:

    Class method call returns sum 7 [OK]
Hint: Class methods called on class, so Calculator.add works [OK]
Common Mistakes:
  • Trying to call add on an instance
  • Confusing string concatenation with addition
  • Expecting error due to method definition
4. Find the error in this Ruby class method definition:
class Person
  def self.say_hello
    puts "Hello!"
  end

  def self.say_goodbye
    puts "Goodbye!"
  end

  def say_hello
    puts "Hi!"
  end
end

Person.say_hello
Person.say_goodbye
Person.new.say_hello
Person.say_hello()
medium
A. Calling Person.say_hello() with parentheses causes error
B. No error, all calls are valid
C. Person.say_hello is both class and instance method causing conflict
D. Person.new.say_hello calls instance method correctly, no error

Solution

  1. Step 1: Analyze method definitions

    There are two class methods self.say_hello and self.say_goodbye, and one instance method say_hello.
  2. Step 2: Check method calls

    Calling Person.say_hello calls the class method. Person.new.say_hello calls the instance method. Parentheses in Person.say_hello() are allowed in Ruby.
  3. Final Answer:

    No error, all calls are valid -> Option B
  4. Quick Check:

    Class and instance methods coexist without conflict [OK]
Hint: Class and instance methods can share names without error [OK]
Common Mistakes:
  • Assuming parentheses cause errors in method calls
  • Thinking class and instance methods with same name conflict
  • Expecting error when calling class method with parentheses
5. You want to create a Ruby class Counter that keeps track of how many times its class method increment is called. Which code correctly implements this behavior?
hard
A. class Counter def self.increment @count ||= 0 @count += 1 end def self.count @count end end
B. class Counter @count = 0 def increment @count += 1 end def count @count end end
C. class Counter def self.increment @@count += 1 end def self.count @@count end end
D. class Counter def increment @@count ||= 0 @@count += 1 end def count @@count end end

Solution

  1. Step 1: Understand class variable vs class instance variable

    Using @@count is a class variable shared across subclasses, but @count inside class methods is a class instance variable, safer for this use.
  2. Step 2: Check method definitions

    class Counter def self.increment @count ||= 0 @count += 1 end def self.count @count end end uses @count ||= 0 inside the class method to initialize the class instance variable, then increments it. It also provides a class method count to read the value.
  3. Final Answer:

    class Counter def self.increment @count ||= 0 @count += 1 end def self.count @count end end -> Option A
  4. Quick Check:

    Use class instance variable @count inside self methods [OK]
Hint: Use @count with ||= inside self methods to track class state [OK]
Common Mistakes:
  • Using instance methods to change class state
  • Using @@count without initialization causing errors
  • Confusing instance variables with class variables
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard