Bird
0
0

How can you combine class instance variables with inheritance to have each subclass track its own count of instances created?

hard📝 Application Q9 of 15
Ruby - Class Methods and Variables
How can you combine class instance variables with inheritance to have each subclass track its own count of instances created?
ADefine @count only in the parent class and increment it in initialize.
BUse a single @@count variable shared by all subclasses.
CDefine @count in each class and increment it in initialize using self.class.instance_variable_set.
DUse a global variable to track counts per subclass.
Step-by-Step Solution
Solution:
  1. Step 1: Understand class instance variables are separate per class

    Each subclass has its own @count variable if defined separately.
  2. Step 2: Increment @count in initialize using self.class

    Using self.class.instance_variable_set/get allows each subclass to update its own count.
  3. Final Answer:

    Define @count in each class and increment it in initialize using self.class.instance_variable_set. -> Option C
  4. Quick Check:

    Subclass tracking with class instance vars = Define @count in each class and increment it in initialize using self.class.instance_variable_set. [OK]
Quick Trick: Each subclass has own class instance vars, increment via self.class [OK]
Common Mistakes:
  • Using @@count which is shared across subclasses
  • Using global variables which are not class-specific
  • Incrementing only parent class variable ignoring subclasses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes