Bird
0
0

Find the error in this Ruby code:

medium📝 Debug Q6 of 15
Ruby - Operators and Expressions
Find the error in this Ruby code:
class Counter
  def initialize
    @count = 0
  end
  def +(value)
    @count += value
  end
end
c = Counter.new
c + 5
puts c
AWrong operator method name
BMissing return value in + method
CCannot print object directly without to_s method
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check printing object

    Printing c calls to_s, which is not defined.
  2. Step 2: Understand default behavior

    Without to_s, Ruby prints object id, not count value.
  3. Final Answer:

    Cannot print object directly without to_s method -> Option C
  4. Quick Check:

    Printing object needs to_s = A [OK]
Quick Trick: Define to_s to print object meaningfully [OK]
Common Mistakes:
  • Assuming + method must return value
  • Thinking operator method name is wrong
  • Believing code runs without printing issue

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes