Complete the code to define a class variable @@count initialized to 0.
class Example [1] = 0 end
Class variables in Ruby start with @@. So @@count is the correct way to define it.
Complete the method to increase the class variable @@count by 1.
class Example @@count = 0 def self.increment [1] end end
To increase the class variable, use @@count += 1. Instance or global variables won't work here.
Fix the error in accessing the class variable inside an instance method.
class Example @@count = 0 def increment [1] end end
Class variables must be accessed with @@ even inside instance methods.
Fill both blanks to show how class variables are shared across subclasses.
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
Class variables are shared among a class and its subclasses, so both increments use += to add 1.
Fill both blanks to demonstrate the danger of class variables being shared unexpectedly.
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]
Changing @@value in Child changes it for Parent too, because class variables are shared. So Parent.value becomes 20.