0
0
Rubyprogramming~10 mins

Class variables (@@) and their dangers in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a class variable @@count initialized to 0.

Ruby
class Example
  [1] = 0
end
Drag options to blanks, or click blank then click option'
Acount
B@count
C$count
D@@count
Attempts:
3 left
💡 Hint
Common Mistakes
Using @count instead of @@count
Using $count which is a global variable
Not using any symbol before count
2fill in blank
medium

Complete the method to increase the class variable @@count by 1.

Ruby
class Example
  @@count = 0
  def self.increment
    [1]
  end
end
Drag options to blanks, or click blank then click option'
A@@count += 1
B@count += 1
Ccount += 1
D$count += 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using @count which is an instance variable
Using $count which is a global variable
Forgetting to use += 1
3fill in blank
hard

Fix the error in accessing the class variable inside an instance method.

Ruby
class Example
  @@count = 0
  def increment
    [1]
  end
end
Drag options to blanks, or click blank then click option'
A@@count += 1
Bself.count += 1
Ccount += 1
D@count += 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using @count which is an instance variable
Trying to call self.count without a method
Using count without any prefix
4fill in blank
hard

Fill both blanks to show how class variables are shared across subclasses.

Ruby
class Parent
  @@count = 0
  def self.increment
    @@count [1] 1
  end
  def self.count
    @@count
  end
end

class Child < Parent
  def self.increment_child
    @@count [2] 1
  end
end
Drag options to blanks, or click blank then click option'
A+=
B-=
C*=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= which subtracts instead of adds
Using *= or /= which change the value differently
5fill in blank
hard

Fill both blanks to demonstrate the danger of class variables being shared unexpectedly.

Ruby
class Parent
  @@value = 10
  def self.value
    @@value
  end
  def self.value=(val)
    @@value = val
  end
end

class Child < Parent
  def self.change_value
    @@value [1] 20
  end
end

Parent.value = 15
Child.change_value
puts Parent.value  # Output: [2]
Drag options to blanks, or click blank then click option'
A=
B+=
C-
D20
Attempts:
3 left
💡 Hint
Common Mistakes
Using += instead of = changes value differently
Expecting Parent.value to stay 15 after Child changes it
Predicting the wrong output (e.g. 15)