Bird
0
0

Identify the problem in this Ruby code using class variables:

medium📝 Debug Q14 of 15
Ruby - Class Methods and Variables
Identify the problem in this Ruby code using class variables:
class A
  @@count = 0
  def initialize
    @@count += 1
  end
  def self.count
    @@count
  end
end

class B < A
  def initialize
    @@count += 10
  end
end

A.new
B.new
puts A.count
AThe code has a syntax error in class B definition.
BThe class variable @@count is not initialized properly.
CThe class variable @@count is shared and modified differently causing unexpected count.
DThe method self.count is missing a return statement.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze class variable usage in inheritance

    Both classes A and B share the same @@count. A#initialize adds 1, B#initialize adds 10.
  2. Step 2: Understand the effect on count

    Creating A.new adds 1, then B.new adds 10, so total @@count becomes 11, which may be unexpected if counting instances separately.
  3. Final Answer:

    The class variable @@count is shared and modified differently causing unexpected count. -> Option C
  4. Quick Check:

    Shared @@count causes tricky bugs [OK]
Quick Trick: Shared @@ variables cause unexpected cross-class changes [OK]
Common Mistakes:
  • Thinking @@count is separate per class
  • Ignoring inheritance effect on @@ variables
  • Assuming initialize methods don't affect shared vars

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes