liveBook · Manning

To_s

As explained in The Well-Grounded Rubyist, Fourth Edition

to_s is a Ruby conversion method that returns a string representation of its receiver.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains automatic calls, custom overrides, array behavior, related converters, and historical Time formatting, but not conversion internals.
Examples
Demonstrates strings, arrays, generic objects, singleton overrides, interpolation, array output, and Time formatting.
What it assumes
Assumes basic Ruby objects and methods, while teaching the to_* conversion pattern and automatic string conversion from concrete examples.
What you can do after
Apply via Ruby's puts, interpolation, explicit conversion, and custom to_s methods while recognizing array and Time formatting differences.
How it connects
Connects to Object, BasicObject, puts, string interpolation, arrays, inspect, display, Time, Active Support, and to_formatted_s.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.