Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Class Methods and Variables
What will be the output of the following Ruby code?
class Parent
  @@value = 1
  def self.value
    @@value
  end
  def self.value=(v)
    @@value = v
  end
end

class Child < Parent
end

Parent.value = 5
puts Child.value
A5
BError
Cnil
D1
Step-by-Step Solution
Solution:
  1. Step 1: Understand class variable sharing

    The class variable @@value is shared between Parent and Child classes.
  2. Step 2: Trace the assignment and output

    Setting Parent.value = 5 changes @@value to 5 for both classes. So, Child.value returns 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Class variables shared, so Child.value = 5 [OK]
Quick Trick: Class variables share values across subclasses [OK]
Common Mistakes:
  • Assuming Child has its own separate @@value
  • Expecting default value 1 after change
  • Confusing class variables with instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes