Bird
0
0

You want to count how many times a class method is called across a class and all its subclasses in Ruby. Which approach is best?

hard📝 Application Q8 of 15
Ruby - Class Methods and Variables
You want to count how many times a class method is called across a class and all its subclasses in Ruby. Which approach is best?
AUse a class instance variable in the superclass and increment it in the method, ensuring subclasses call super
BUse a class variable (@@count) in the superclass and increment it in the method
CDefine an instance variable in each subclass and increment it in the method
DUse a global variable to track calls across all classes
Step-by-Step Solution
Solution:
  1. Step 1: Understand inheritance of class variables

    Class variables (@@count) are shared across a class and its subclasses in Ruby.
  2. Step 2: Use class variable for counting

    Incrementing @@count in the superclass method will track calls from all subclasses automatically.
  3. Step 3: Evaluate other options

    Class instance variables are not shared with subclasses; instance variables are per object; global variables are discouraged.
  4. Final Answer:

    Use a class variable (@@count) in the superclass and increment it in the method -> Option B
  5. Quick Check:

    Class variables are shared across subclasses [OK]
Quick Trick: Class variables are shared across subclasses [OK]
Common Mistakes:
  • Using class instance variables expecting inheritance
  • Using global variables unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes