Bird
0
0

What is wrong with this to_s method?

medium📝 Debug Q7 of 15
Ruby - Classes and Objects
What is wrong with this to_s method?
class Item
  def to_s
    puts "Item description"
  end
end

puts Item.new.to_s
Aputs cannot be used inside to_s
BClass Item cannot have to_s method
Cto_s method must have parameters
Dto_s should return a string, not print it
Step-by-Step Solution
Solution:
  1. Step 1: Understand to_s method role

    The to_s method should return a string, not print it.
  2. Step 2: Analyze the code behavior

    Using puts inside to_s prints the string but returns nil, so puts Item.new.to_s prints an empty line after.
  3. Final Answer:

    to_s should return a string, not print it -> Option D
  4. Quick Check:

    to_s must return string, not output directly [OK]
Quick Trick: Return string in to_s; don't use puts inside it [OK]
Common Mistakes:
  • Using puts inside to_s
  • Expecting puts to return string
  • Thinking to_s needs parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes