Bird
0
0

How can you modify this Ruby class to keep track of how many objects have been created using class instance variables?

hard📝 Application Q15 of 15
Ruby - Class Methods and Variables
How can you modify this Ruby class to keep track of how many objects have been created using class instance variables?
class Bird
  def initialize
    # increment count here
  end

  def self.count
    @count
  end
end
AAdd <code>@count = 0</code> outside methods and increment <code>@count</code> inside a class method called from initialize
BUse <code>@@count</code> variable and increment it inside initialize
CDefine <code>@count</code> inside initialize and increment it
DAdd <code>self.count += 1</code> inside initialize
Step-by-Step Solution
Solution:
  1. Step 1: Initialize class instance variable

    Define @count = 0 inside the class but outside methods to store count.
  2. Step 2: Increment count via class method

    Create a class method to increment @count and call it inside initialize to update count on each new object.
  3. Final Answer:

    Add @count = 0 outside methods and increment @count inside a class method called from initialize -> Option A
  4. Quick Check:

    Class instance var + class method increment = object count [OK]
Quick Trick: Use class method to update class instance variable from initialize [OK]
Common Mistakes:
  • Using class variables @@count instead of class instance variables
  • Trying to increment @count directly inside initialize without class method
  • Defining @count inside initialize which resets it each time

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes