Bird
0
0

Identify the issue in this Ruby code:

medium📝 Debug Q6 of 15
Ruby - Class Methods and Variables
Identify the issue in this Ruby code:
class Sample
  @@count = 5
  def self.count
    @count
  end
end

puts Sample.count
AThe method should be an instance method, not a class method
BThe class variable @@count is not initialized
CThe class method accesses an instance variable instead of the class variable
DThe code will raise a syntax error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable usage

    The class method self.count accesses @count, which is a class instance variable, not the class variable @@count.
  2. Step 2: Understand variable scope

    @@count is a class variable shared across the class and instances, but @count here is nil because it was never set.
  3. Final Answer:

    The class method accesses an instance variable instead of the class variable -> Option C
  4. Quick Check:

    Class variables use @@, instance variables use @ [OK]
Quick Trick: Class methods need correct variable scope (@@ vs @) [OK]
Common Mistakes:
  • Assuming @count and @@count are the same
  • Expecting class variables to be accessed via @

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes