Bird
0
0

Consider this Ruby class: class Counter def initialize @count = 0 end def increment @count += 1 end def reset @count = 0 end def current @count end end What will be the output after this code?

hard📝 Application Q9 of 15
Ruby - Classes and Objects
Consider this Ruby class: class Counter def initialize @count = 0 end def increment @count += 1 end def reset @count = 0 end def current @count end end What will be the output after this code? c = Counter.new c.increment c.increment puts c.current c.reset puts c.current
A2\n0
B0\n2
C1\n0
DError: undefined method
Step-by-Step Solution
Solution:
  1. Step 1: Trace increments

    c.increment called twice increases @count from 0 to 2.
  2. Step 2: Output current and reset

    puts c.current prints 2, then reset sets @count to 0, then puts c.current prints 0.
  3. Final Answer:

    2\n0 -> Option A
  4. Quick Check:

    Instance variable updates persist across method calls [OK]
Quick Trick: Instance variables keep state across method calls [OK]
Common Mistakes:
  • Assuming @count resets automatically
  • Confusing local variables with instance variables
  • Forgetting to use @ in increment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes