Bird
0
0

What is the issue with this Ruby code?

medium📝 Debug Q7 of 15
Ruby - Operators and Expressions
What is the issue with this Ruby code?
class Coordinate
  attr_reader :x, :y
  def initialize(x, y)
    @x, @y = x, y
  end
  def +(other)
    Coordinate.new(@x + other.x, @y + other.y)
  end
end
c1 = Coordinate.new(2, 3)
c2 = Coordinate.new(4, 5)
puts c1 + c2
AThe <code>puts</code> call tries to print an object without a <code>to_s</code> method
BThe <code>+</code> method is missing a return statement
CThe <code>attr_reader</code> is incorrectly defined
DThe <code>initialize</code> method does not assign instance variables
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the + method

    The + method correctly returns a new Coordinate object with summed coordinates.
  2. Step 2: Check the puts call

    Calling puts on an object prints its to_s representation. Since Coordinate does not define to_s, it prints the default object info.
  3. Final Answer:

    The puts call tries to print an object without a to_s method -> Option A
  4. Quick Check:

    Printing objects requires a to_s method [OK]
Quick Trick: Objects need to_s for readable puts output [OK]
Common Mistakes:
  • Assuming + method must explicitly return
  • Believing attr_reader is incorrect
  • Thinking initialize does not assign variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes