Bird
0
0

You want to keep track of how many times a class method call is invoked in class Service. Which code correctly implements this using self. methods and a class instance variable?

hard📝 Application Q8 of 15
Ruby - Class Methods and Variables
You want to keep track of how many times a class method call is invoked in class Service. Which code correctly implements this using self. methods and a class instance variable?
Aclass Service @calls = 0 def self.call @calls += 1 end def self.calls @calls end end
Bclass Service @@calls = 0 def call @@calls += 1 end def calls @@calls end end
Cclass Service def self.call calls += 1 end def self.calls calls end end
Dclass Service def call @calls += 1 end def calls @calls end end
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct use of class instance variable and class methods

    class Service @calls = 0 def self.call @calls += 1 end def self.calls @calls end end uses @calls as a class instance variable and increments it inside class method self.call.
  2. Step 2: Check other options for errors

    class Service @@calls = 0 def call @@calls += 1 end def calls @@calls end end uses class variables and instance methods incorrectly; Options C and D have syntax or scope errors.
  3. Final Answer:

    Option A correctly tracks calls using class instance variable and class methods. -> Option A
  4. Quick Check:

    Use class instance vars with self. methods for tracking [OK]
Quick Trick: Use @var with self. methods to track class-level data [OK]
Common Mistakes:
  • Using instance methods to update class variables
  • Confusing class variables (@@) with class instance variables (@)
  • Missing self. prefix for class methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes