Bird
Raised Fist0
Rubyprogramming~10 mins

Class methods with self prefix in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Class methods with self prefix
Define class
↓
Define method with self.
↓
Call method on class
↓
Execute method body
↓
Return result
↓
Output result
This flow shows how a class method defined with self. is called on the class itself and executes its code.
Execution Sample
Ruby
class Greeting
  def self.say_hello
    "Hello from class method!"
  end
end

puts Greeting.say_hello
Defines a class method say_hello and calls it on the Greeting class to print a message.
Execution Table
StepActionEvaluationResult
1Define class GreetingClass Greeting createdClass Greeting ready
2Define method self.say_helloMethod say_hello added to Greeting classMethod ready
3Call Greeting.say_helloInvoke class methodMethod body runs
4Execute method bodyReturn string "Hello from class method!""Hello from class method!"
5puts outputPrint string to consoleHello from class method!
💡 Method returns string and program ends after printing output
Variable Tracker
VariableStartAfter callFinal
GreetingClass definedClass existsClass exists
say_hello (method)Not definedDefined on GreetingDefined on Greeting
Return valueNoneNone"Hello from class method!"
Key Moments - 2 Insights
Why do we use self. before method name?
Using self. defines the method as a class method, so it belongs to the class itself, not instances. See execution_table step 2 where method is added to class.
Can we call say_hello without self. prefix?
No, without self. it becomes an instance method. Here, we call Greeting.say_hello on the class, so method must be defined with self. (see step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result returned by the class method at step 4?
Anil
BAn error
C"Hello from class method!"
D"say_hello"
💡 Hint
Check the 'Result' column at step 4 in execution_table
At which step is the method say_hello defined as a class method?
AStep 2
BStep 3
CStep 1
DStep 5
💡 Hint
Look at the 'Action' column for method definition in execution_table
If we remove self. from method definition, what will happen when calling Greeting.say_hello?
AIt will print the message as before
BIt will raise a NoMethodError
CIt will call an instance method automatically
DIt will return nil
💡 Hint
Recall key_moments about method type and how class methods are called
Concept Snapshot
Class methods use self. prefix in method definition.
Called on the class itself, not instances.
Syntax: def self.method_name
Use for behavior related to the class as a whole.
Called like ClassName.method_name.
Without self., methods are instance methods.
Full Transcript
This example shows how to define and call a class method in Ruby using the self. prefix. The class Greeting is defined, then a method say_hello is defined with self. to make it a class method. When we call Greeting.say_hello, Ruby runs the method body and returns the string "Hello from class method!" which is printed. The execution table traces each step: defining the class, defining the method, calling the method, returning the string, and printing it. The variable tracker shows the class and method states. Key moments clarify why self. is needed and what happens if it is removed. The quiz tests understanding of the method return value, definition step, and behavior without self. The snapshot summarizes the key points about class methods with self. prefix.

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