Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Class Methods and Variables
What will be the output of this Ruby code?
class Dog
  @@count = 0
  def initialize
    @@count += 1
  end
  def self.count
    @@count
  end
end

Dog.new
Dog.new
puts Dog.count
A2
B0
C1
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand class variable usage

    @@count is a class variable shared by all Dog instances. It starts at 0.
  2. Step 2: Count increments on each new Dog

    Each Dog.new calls initialize, which adds 1 to @@count. Two Dog.new calls increase @@count to 2.
  3. Step 3: Output the class variable

    Dog.count returns @@count, which is 2, so puts prints 2.
  4. Final Answer:

    2 -> Option A
  5. Quick Check:

    Class variable increments twice = 2 [OK]
Quick Trick: Class variables track shared data across all instances [OK]
Common Mistakes:
  • Thinking @@count resets for each object
  • Confusing class variables with instance variables
  • Expecting an error from @@count usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes