Bird
0
0

What will be the output of the following Ruby code?

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

class Child < Parent
  @@value = 20
end

puts Parent.value
puts Child.value
A10 20
B20 20
C10 10
DError: class variable redefinition
Step-by-Step Solution
Solution:
  1. Step 1: Understand class variable sharing

    @@value is shared between Parent and Child classes.
  2. Step 2: Analyze assignment in Child

    Child sets @@value to 20, which changes the shared variable for both classes.
  3. Step 3: Check output of Parent.value and Child.value

    Both calls return 20 because @@value is shared and last set to 20.
  4. Final Answer:

    20 20 -> Option B
  5. Quick Check:

    Shared @@value reflects last assignment [OK]
Quick Trick: Class variables shared, last assignment wins [OK]
Common Mistakes:
  • Expecting separate values for Parent and Child
  • Thinking redefinition causes error
  • Confusing class variables with class instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes