0
0
Rubyprogramming~5 mins

Class instance variables as alternative in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A$
B@
C@@
D#
What is a key advantage of using class instance variables over class variables?
AThey are shared with subclasses
BThey are global variables
CThey prevent data sharing between classes and subclasses
DThey can be accessed without methods
How can you access a class instance variable inside a class method?
AUsing variable without prefix
BUsing @@variable
CUsing $variable
DUsing @variable
Can instance methods directly access class instance variables?
ANo, they must use self.class to access them
BYes, directly with @variable
CYes, with @@variable
DNo, they cannot access them at all
Where are class instance variables stored in Ruby?
AIn the class object itself
BIn each instance of the class
CIn global memory
DIn the superclass only
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.