0
0
Rubyprogramming~5 mins

Class variables (@@) and their dangers in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a class variable in Ruby?
A class variable in Ruby is a variable shared among a class and all its subclasses. It is prefixed with @@ and holds data common to the class hierarchy.
Click to reveal answer
beginner
How do you declare a class variable in Ruby?
You declare a class variable by prefixing the variable name with @@ inside a class, for example: @@count = 0
Click to reveal answer
intermediate
Why can class variables (@@) be dangerous in Ruby?
Class variables are dangerous because they are shared across the entire class hierarchy, so changes in one subclass affect others unexpectedly, leading to bugs that are hard to track.
Click to reveal answer
intermediate
What is a safer alternative to class variables in Ruby?
Using class instance variables (e.g., @count inside class << self or self methods) is safer because they belong only to the specific class, not shared with subclasses.
Click to reveal answer
advanced
Explain with an example how class variables can cause unexpected behavior.
If a superclass and its subclass both modify @@var, the changes affect each other. For example, if superclass sets @@count = 1 and subclass sets @@count = 5, both see the last value 5, which can cause confusion.
Click to reveal answer
What symbol is used to declare a class variable in Ruby?
A@
B@@
C$
D#
What is a main risk of using class variables (@@) in Ruby?
AThey are shared across subclasses, causing unexpected side effects.
BThey cannot be accessed inside instance methods.
CThey are slower than local variables.
DThey are private by default.
Which is a safer alternative to class variables for storing class-specific data?
AClass instance variables (@var)
BGlobal variables ($var)
CLocal variables (var)
DConstants (VAR)
If a superclass and subclass both modify @@var, what happens?
AAn error is raised.
BEach has its own separate @@var.
CThe subclass cannot access @@var.
DThey share the same @@var, so changes affect both.
How do you access a class instance variable inside a class method?
AUse $var inside the class method.
BUse @@var inside the class method.
CUse @var inside the class method.
DUse var without any prefix.
Describe what class variables (@@) are in Ruby and why they can cause problems in inheritance.
Think about how one change affects all related classes.
You got /4 concepts.
    Explain the difference between class variables (@@) and class instance variables (@) in Ruby.
    Focus on scope and sharing of data.
    You got /4 concepts.