to_s returns a string representation of its receiver. Every Ruby object except BasicObject responds to it, although the representation ranges from an unchanged string to a code-like or diagnostic description. section 7.4.1 section 7.4
Ruby often calls to_s for you. puts converts its arguments, and string interpolation converts embedded objects. You can also call the method explicitly when you need the representation directly. section 7.4.1
Customizing an object's display
obj = Object.new def obj.to_s "I'm an object!" end puts obj # I'm an object! "My object says: #{obj}" # "My object says: I'm an object!" A class can define to_s for all its instances, while an individual object can override the method on itself. Arrays are a notable edge case: puts prints their elements one per line, whereas array.to_s returns a bracketed representation. section 7.4.1
to_s belongs to Ruby's broader conversion family, alongside to_sym, to_a, to_i, and to_f; objects do not necessarily implement every converter. inspect serves a related but distinct role for representations, while display writes a string directly to an output stream. section 7.4 section 7.4.1
Overriding core to_s methods can preserve existing behavior while adding formatting options, but the older Active Support Time#to_s override was removed because it could disable a Ruby interpolation optimization; use to_formatted_s or to_fs for those formats. section 13.2.3
