0
0
Rubyprogramming~20 mins

Class variables (@@) and their dangers in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Class Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A0
B1
C2
D3
Attempts:
2 left
💡 Hint
Remember that class variables (@@) are shared across the class hierarchy.
Predict Output
intermediate
2: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
AB
BA
Cnil
DError
Attempts:
2 left
💡 Hint
Class variables are shared, so changing in subclass affects superclass.
🔧 Debug
advanced
3: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
AThe code raises a NameError because @@data is undefined in Child
BBoth Parent and Child share the same @@data array, so both show ['parent1', 'child1']
CParent and Child have separate @@data arrays, so Parent shows ['parent1'] and Child shows ['child1']
DThe code raises a TypeError because @@data is modified in Child
Attempts:
2 left
💡 Hint
Class variables are shared across the inheritance chain, including mutable objects.
📝 Syntax
advanced
2:00remaining
Identifying class variable misuse causing bugs
Which option shows a misuse of class variables that can cause bugs in inheritance?
AUsing @@var to store mutable data shared by subclasses
BUsing instance variables @var in class methods
CUsing constants for fixed values in classes
DUsing local variables inside methods
Attempts:
2 left
💡 Hint
Mutable shared state in class variables can cause unexpected side effects.
🧠 Conceptual
expert
3:00remaining
Why are class variables (@@) considered dangerous in Ruby?
Select the best explanation for why class variables (@@) can be dangerous in Ruby inheritance.
ABecause @@ variables are private and cannot be accessed by subclasses
BBecause @@ variables are only accessible inside instance methods
CBecause @@ variables are shared across the entire inheritance chain, causing unexpected side effects when subclasses modify them
DBecause @@ variables are immutable and cannot be changed once set
Attempts:
2 left
💡 Hint
Think about how shared state affects subclasses.