Recall & Review
beginner
What is a class instance variable in Ruby?A class instance variable is a variable that belongs to the class object itself, not to instances of the class. It is prefixed with a single @ and is used to store data related to the class, separate from instance variables of objects.Click to reveal answer
intermediate
How do class instance variables differ from class variables in Ruby?Class instance variables (@var) belong only to the class object and are not shared with subclasses. Class variables (@@var) are shared among a class and all its subclasses. This makes class instance variables safer for storing class-specific data.Click to reveal answer
beginner
How do you define and access a class instance variable in Ruby?Define a class instance variable inside the class body using @var. Access it with class methods using @var or with self.instance_variable_get(:@var). Example:<br><pre>class MyClass
@count = 0
def self.count
@count
end
end</pre>Click to reveal answer
intermediate
Why might you choose class instance variables over class variables?Class instance variables avoid unexpected sharing of data between a class and its subclasses. This helps prevent bugs when subclasses modify shared data unintentionally. They provide better encapsulation for class-specific state.Click to reveal answer
intermediate
Can class instance variables be accessed from instance methods?No, class instance variables belong to the class object, not to instances. To access them from instance methods, you need to call class methods or use self.class to reach the class and then access the variable.Click to reveal answer
Which symbol prefix is used for class instance variables in Ruby?
✗ Incorrect
Class instance variables use a single @ prefix, while class variables use @@.
What is a key advantage of using class instance variables over class variables?
✗ Incorrect
Class instance variables are not shared with subclasses, preventing unintended data sharing.
How can you access a class instance variable inside a class method?
✗ Incorrect
Inside class methods, class instance variables are accessed with a single @ prefix.
Can instance methods directly access class instance variables?
✗ Incorrect
Instance methods must use self.class to access class instance variables.
Where are class instance variables stored in Ruby?
✗ Incorrect
Class instance variables are stored in the class object itself, separate from instances.
Explain what class instance variables are and how they differ from class variables in Ruby.
Think about where the variable lives and who can see it.
You got /3 concepts.
Describe how to define and access a class instance variable in Ruby, including from instance methods.
Remember the @ prefix and how instance methods reach the class.
You got /3 concepts.