Bird
0
0

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📝 Application Q15 of 15
Ruby - Class Methods and Variables
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?
Aclass Counter def self.increment @count ||= 0 @count += 1 end def self.count @count end end
Bclass Counter @count = 0 def increment @count += 1 end def count @count end end
Cclass Counter def self.increment @@count += 1 end def self.count @@count end end
Dclass Counter def increment @@count ||= 0 @@count += 1 end def count @@count end end
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes