Bird
0
0

Given the following Ruby code:

medium📝 Predict Output Q5 of 15
Ruby - Class Methods and Variables
Given the following Ruby code:
class X
  @@counter = 0
  def initialize
    @@counter += 1
  end
  def self.counter
    @@counter
  end
end

class Y < X; end

X.new
Y.new
Y.new
puts Y.counter

What will be the output?
A3
B2
C1
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand class variable sharing

    Class variables (@@counter) are shared between a class and all its subclasses.
  2. Step 2: Count increments

    Each new call increments the shared @@counter by 1. Three instances are created in total.
  3. Step 3: Accessing counter

    Calling Y.counter returns the shared @@counter value, which is 3.
  4. Final Answer:

    3 -> Option A
  5. Quick Check:

    Class variables are shared across subclasses [OK]
Quick Trick: Class variables shared across subclasses count all instances [OK]
Common Mistakes:
  • Assuming subclasses have separate class variable copies
  • Expecting Y.counter to return 2 instead of 3
  • Confusing class variables with instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes