Bird
0
0

How do you correctly override the to_s method in a Ruby class to return a custom string?

easy📝 Syntax Q3 of 15
Ruby - Classes and Objects
How do you correctly override the to_s method in a Ruby class to return a custom string?
Adef to_s; print "Custom string"; end
Bdef to_s() puts "Custom string" end
Cdef to_s; "Custom string"; end
Ddef to_s; return puts "Custom string"; end
Step-by-Step Solution
Solution:
  1. Step 1: Understand method overriding

    Overriding to_s requires returning a string, not printing it.
  2. Step 2: Analyze options

    def to_s; "Custom string"; end returns the string directly. Options B, C, and D use puts or print, which output to console but return nil or unexpected values.
  3. Final Answer:

    def to_s; "Custom string"; end -> Option C
  4. Quick Check:

    puts obj.to_s prints the returned string [OK]
Quick Trick: to_s must return string, not print it [OK]
Common Mistakes:
  • Using puts inside to_s instead of returning a string
  • Not returning any value from to_s

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes