liveBook · Manning

String conversion

As explained in The Well-Grounded Rubyist, Fourth Edition

String conversion is the derivation of a string or another object representing a string value in a different form.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains automatic calls, custom definitions, related methods, array exceptions, and regexp notation without exhaustive API coverage.
Examples
Uses irb expressions, a customized Object instance, array output, file output, and regular-expression representations.
What it assumes
Assumes familiarity with Ruby objects, methods, puts, interpolation, and regular expressions.
What you can do after
Apply it via Ruby's to_s, puts, interpolation, inspect, display, and custom representation methods.
How it connects
Connects to Ruby objects, BasicObject, puts, string interpolation, inspect, display, arrays, and regular expressions.

Also explained in

Compare how 2 books explain string conversion →

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.