Challenge - 5 Problems
Ruby Class Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Class methods are defined with
self. and called on the class itself.✗ Incorrect
The method
add is a class method because it is defined with self.add. Calling Calculator.add(3, 4) returns the sum 7.❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Instance methods need an object to be called on.
✗ Incorrect
The method
greet is an instance method. Calling Person.greet tries to call it on the class, which causes an error.🔧 Debug
advanced2: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
Attempts:
2 left
💡 Hint
Class methods do not have access to instance variables because they belong to the class, not an object.
✗ Incorrect
Instance variables like
@length belong to objects. Class methods run on the class itself and cannot access these instance variables.📝 Syntax
advanced2:00remaining
Identify the correct class method syntax
Which option correctly defines a class method named
info in Ruby?Attempts:
2 left
💡 Hint
Class methods use
self.method_name syntax.✗ Incorrect
Option B correctly uses
def self.info to define a class method. Option B has wrong parameter syntax. Option B has invalid colon syntax. Option B defines an instance method.🚀 Application
expert2: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
Attempts:
2 left
💡 Hint
Class instance variables (@variables at class level) are accessible in class methods.
✗ Incorrect
The class instance variable
@calls is initialized to 0 at class level. Class methods can access and modify it. count_calls is executed 3 times, incrementing @calls to 3, which Counter.calls returns.