Challenge - 5 Problems
Ruby Class Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Understanding class variable sharing
What is the output of this Ruby code involving class variables?
Ruby
class Parent @@count = 0 def self.increment @@count += 1 end def self.count @@count end end class Child < Parent def self.increment @@count += 2 end end Parent.increment Child.increment puts Parent.count
Attempts:
2 left
💡 Hint
Remember that class variables (@@) are shared across the class hierarchy.
✗ Incorrect
The class variable @@count is shared between Parent and Child classes. Parent.increment adds 1, then Child.increment adds 2, so total is 3.
❓ Predict Output
intermediate2:00remaining
Effect of modifying class variable in subclass
What will this Ruby code print?
Ruby
class A @@var = 'A' def self.var @@var end end class B < A @@var = 'B' end puts A.var
Attempts:
2 left
💡 Hint
Class variables are shared, so changing in subclass affects superclass.
✗ Incorrect
Assigning @@var = 'B' in subclass B changes the shared class variable for both classes. So A.var returns 'B'.
🔧 Debug
advanced3:00remaining
Why does this class variable cause unexpected behavior?
Consider this Ruby code. Why does the output show unexpected shared state?
Ruby
class Parent @@data = [] def self.add(item) @@data << item end def self.data @@data end end class Child < Parent end Parent.add('parent1') Child.add('child1') puts Parent.data.inspect puts Child.data.inspect
Attempts:
2 left
💡 Hint
Class variables are shared across the inheritance chain, including mutable objects.
✗ Incorrect
Class variable @@data is shared between Parent and Child. Adding items from either class modifies the same array, so both show all added items.
📝 Syntax
advanced2:00remaining
Identifying class variable misuse causing bugs
Which option shows a misuse of class variables that can cause bugs in inheritance?
Attempts:
2 left
💡 Hint
Mutable shared state in class variables can cause unexpected side effects.
✗ Incorrect
Using @@var to hold mutable data shared by subclasses can cause bugs because changes in one subclass affect others unexpectedly.
🧠 Conceptual
expert3:00remaining
Why are class variables (@@) considered dangerous in Ruby?
Select the best explanation for why class variables (@@) can be dangerous in Ruby inheritance.
Attempts:
2 left
💡 Hint
Think about how shared state affects subclasses.
✗ Incorrect
Class variables (@@) are shared by a class and all its subclasses, so changes in one place affect all others, leading to hard-to-track bugs.