String conversion derives a string representation of an object, most commonly through to_s. Every Ruby object except BasicObject responds to to_s, and Ruby calls it automatically in contexts such as puts and string interpolation; you can also call it explicitly. section 7.4.1
Customizing an object's displayed form
obj = Object.new puts obj # #<Object:...> 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!" section 7.4.1
Related representation methods serve different purposes:
- to_s supplies a canonical string representation; its result may be ordinary text, a code-like form, or a cryptic object description. section 7.4.1
- inspect and p generally expose a representation useful for examining objects; regular expressions use inspect to show a form closer to their typed notation. section 7.4.1 section 11.6.2
- display writes a string directly, either to standard output or to a supplied file handle, rather than serving as the usual representation mechanism. section 7.4.1
- Arrays are a special case: puts outputs each element on its own line, while array.to_s returns a bracketed representation. section 7.4.1
>> obj = Object.new
=> #<Object:0x000001011c9ce0> 1
>> puts obj
#<Object:0x000001011c9ce0> 2
=> nil
>> def obj.to_s 3
>> "I'm an object!"
>> end
=> :to_s 4
>> puts obj 5
I'm an object!
=> nil
Watch the default object representation change after defining a singleton to_s method, then observe the same representation through puts. section 7.4.1
>> /abc/.inspect
=> "/abc/"
Compare inspect's readable regular-expression form with the alternate form produced by to_s. section 11.6.2

