0
0
Rubyprogramming~20 mins

Class methods with self prefix in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Class Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of class method call
What is the output of this Ruby code?
Ruby
class Calculator
  def self.add(a, b)
    a + b
  end
end

puts Calculator.add(3, 4)
AError: undefined method 'add' for Calculator
B34
Cnil
D7
Attempts:
2 left
💡 Hint
Class methods are defined with self. and called on the class itself.
Predict Output
intermediate
2:00remaining
Calling instance method as class method
What happens when you run this Ruby code?
Ruby
class Person
  def greet
    "Hello!"
  end
end

puts Person.greet
AHello!
Bnil
CError: undefined method 'greet' for Person
DError: wrong number of arguments (given 0, expected 1)
Attempts:
2 left
💡 Hint
Instance methods need an object to be called on.
🔧 Debug
advanced
2:00remaining
Why does this class method fail?
This Ruby code raises an error. Which option explains the cause?
Ruby
class Box
  def self.volume
    @length * @width * @height
  end

  def initialize(length, width, height)
    @length = length
    @width = width
    @height = height
  end
end

puts Box.volume
AClass method cannot access instance variables like @length
BMissing return statement in volume method
CInitialize method is not called automatically for class methods
DClass method volume requires arguments but none given
Attempts:
2 left
💡 Hint
Class methods do not have access to instance variables because they belong to the class, not an object.
📝 Syntax
advanced
2:00remaining
Identify the correct class method syntax
Which option correctly defines a class method named info in Ruby?
A
def info(self)
  "Class info"
end
B
def self.info
  "Class info"
end
C
def info:
  "Class info"
end
D
def info()
  "Class info"
end
Attempts:
2 left
💡 Hint
Class methods use self.method_name syntax.
🚀 Application
expert
2:00remaining
How many times is the class method called?
Consider this Ruby code. How many times is the class method count_calls executed?
Ruby
class Counter
  @calls = 0

  def self.count_calls
    @calls += 1
  end

  def self.calls
    @calls
  end
end

3.times { Counter.count_calls }

puts Counter.calls
A3
B0
C1
DError: undefined method '+' for nil
Attempts:
2 left
💡 Hint
Class instance variables (@variables at class level) are accessible in class methods.