Bird
Raised Fist0
Rubyprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is a key characteristic of Ruby class variables (@@)?
easy
A. They are unique to each instance of a class.
B. They are shared among a class and all its subclasses.
C. They are only accessible inside instance methods.
D. They behave like local variables inside methods.

Solution

  1. Step 1: Understand class variable scope

    Class variables (@@) are shared across a class and all its subclasses, meaning they hold the same value for all related classes.
  2. Step 2: Compare with other variable types

    Instance variables are unique per object, local variables are method-specific, so they don't share data like class variables do.
  3. Final Answer:

    They are shared among a class and all its subclasses. -> Option B
  4. Quick Check:

    Class variables share data across class hierarchy [OK]
Hint: Remember @@ means shared across class and subclasses [OK]
Common Mistakes:
  • Confusing class variables with instance variables
  • Thinking @@ variables are local to instances
  • Assuming @@ variables are private to one class
2. Which of the following is the correct syntax to define and use a class variable in Ruby?
easy
A. class MyClass @@count = 0 end
B. class MyClass @count = 0 end
C. class MyClass $count = 0 end
D. class MyClass count = 0 end

Solution

  1. Step 1: Identify class variable syntax

    Class variables start with @@, so @@count = 0 is correct for defining a class variable.
  2. Step 2: Differentiate other variable types

    @count is an instance variable, $count is a global variable, and count alone is a local variable.
  3. Final Answer:

    class MyClass @@count = 0 end -> Option A
  4. Quick Check:

    Class variable syntax uses @@ [OK]
Hint: Class variables always start with @@ [OK]
Common Mistakes:
  • Using @ instead of @@ for class variables
  • Confusing global variables ($) with class variables
  • Defining variables without any prefix
3. 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
medium
A. 5
B. Error
C. nil
D. 1

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]
Hint: 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
4. Identify the problem in this Ruby code using class variables:
class A
  @@count = 0
  def initialize
    @@count += 1
  end
  def self.count
    @@count
  end
end

class B < A
  def initialize
    @@count += 10
  end
end

A.new
B.new
puts A.count
medium
A. The code has a syntax error in class B definition.
B. The class variable @@count is not initialized properly.
C. The class variable @@count is shared and modified differently causing unexpected count.
D. The method self.count is missing a return statement.

Solution

  1. Step 1: Analyze class variable usage in inheritance

    Both classes A and B share the same @@count. A#initialize adds 1, B#initialize adds 10.
  2. Step 2: Understand the effect on count

    Creating A.new adds 1, then B.new adds 10, so total @@count becomes 11, which may be unexpected if counting instances separately.
  3. Final Answer:

    The class variable @@count is shared and modified differently causing unexpected count. -> Option C
  4. Quick Check:

    Shared @@count causes tricky bugs [OK]
Hint: Shared @@ variables cause unexpected cross-class changes [OK]
Common Mistakes:
  • Thinking @@count is separate per class
  • Ignoring inheritance effect on @@ variables
  • Assuming initialize methods don't affect shared vars
5. You want to track the number of instances created separately for two subclasses without interference. Which approach avoids the dangers of class variables (@@)?
hard
A. Use a local variable inside the initialize method to count instances.
B. Use a global variable ($count) shared by all classes.
C. Use class variables (@@count) but reset them in each subclass initialize.
D. Use class instance variables (@count) in each subclass instead of @@count.

Solution

  1. Step 1: Understand the problem with class variables

    Class variables (@@count) are shared across subclasses, causing counts to mix and produce wrong totals.
  2. Step 2: Use class instance variables for separate counts

    Class instance variables (@count) belong to each class separately, so each subclass can track its own count safely.
  3. Final Answer:

    Use class instance variables (@count) in each subclass instead of @@count. -> Option D
  4. Quick Check:

    Class instance vars avoid shared @@ dangers [OK]
Hint: Use @count per class to avoid shared @@count bugs [OK]
Common Mistakes:
  • Using global variables which mix counts globally
  • Trying to reset @@count which is error-prone
  • Using local variables which don't persist counts
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard