Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 134 ยท Object-Oriented Ruby

to_s, inspect and Conversions

Learn the difference between to_s and inspect in Ruby, how puts and p use them, explicit versus implicit conversions (to_str, to_ary, to_proc) and Kernel#Integer, Float, String and Array.

Every Ruby object can turn itself into text, and Ruby has two different methods for it: to_s and inspect. They look similar but serve different readers. to_s produces text for people using your program. inspect produces text for programmers debugging it. Ruby uses one or the other depending on what you call: puts and string interpolation use to_s, while p and the interactive console use inspect.

There is a second half to this topic: conversions between types. Ruby distinguishes explicit conversions (to_s, to_i, to_a), which you call on purpose, from implicit conversions (to_str, to_ary, to_proc, to_hash), which Ruby calls by itself when an object is used where a certain type is required. Understanding that split explains many TypeError messages and lets you build objects that plug into the core library smoothly.

to_s versus inspect

Ruby Two ways to show the same objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The difference is clearest for strings, symbols and nil. "hello".to_s is hello without quotes, but "hello".inspect is "hello" with quotes, so you can tell a string from a symbol or a number when you debug. nil.to_s is an empty string and nil.inspect is the word nil. That is why puts nil prints an empty line and p nil prints nil. puts flattens arrays and prints one element per line; p shows the array in literal form. Note also that p returns its argument, which makes it easy to drop into the middle of an expression while debugging.

When a value looks wrong in output, use p or .inspect. A string "42" and an integer 42 both print 42 with puts, but p shows "42" and 42.

What the default looks like

Objects of your own classes get a default to_s and inspect. The default to_s prints the class name and a memory address, such as #<Point>-style text with a hexadecimal number, and the default inspect adds the instance variables. Since the address changes on every run, you almost never want to show it to users.

Ruby Default output, then your own to_s

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first two lines show #<Point:0x...> and #<Point:0x... @x=1, @y=2> (the program hides the real address with sub so the output is stable). After we define to_s, puts pt and interpolation use our version. Interestingly, inspect does not fall back to a custom to_s: the last line still prints the default form with the instance variables. Ruby treats the two as independent on purpose, so each can be tuned for its reader.

Writing a good inspect

A useful inspect shows the class and the state that matters, in a compact form that makes sense in logs and in the output of p on an array of such objects. The convention is the #<ClassName ...> shape.

Ruby A custom inspect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

By writing inspect ourselves, we hide the @secret_token, which would otherwise appear in every log line and exception message that prints the object. That alone is a good reason to define inspect for classes holding passwords, keys or personal data. Both p and pp use it, and an array of invoices shows [#<Invoice 1001 items=3>, #<Invoice 1001 items=3>]. If you only want to hide some variables from the default format, define a private method instance_variables_to_inspect that returns the names to show (for example [:@number]; it works in Ruby 4.0, but not in older versions), or write inspect by hand as above.

puts calls to_s on whatever it prints. If to_s returns something that is not a String, Ruby ignores your method and prints the default #<ClassName> form, so always return a string.

Explicit conversions: to_s, to_i, to_a and friends

Methods named to_* convert an object to another type on request. They are explicit: you call them. The core types provide a family:

  • to_s (String), to_i (Integer), to_f (Float), to_r (Rational), to_c (Complex)
  • to_sym (Symbol), to_a (Array), to_h (Hash)

They are forgiving. "12abc".to_i returns 12, "abc".to_i returns 0, and nil.to_a returns []. That is convenient but can hide bad input.

Ruby Forgiving to_i versus strict Integer()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Integer() and Float() (these are methods on Kernel that happen to start with a capital letter) are strict: the whole string must be a valid number or they raise ArgumentError. They accept a base for Integer(), allow surrounding whitespace, and with exception: false they return nil instead of raising. Use the forgiving to_i when you are sure about the input or want a default of zero, and Integer() when validating input. The final line fails with main.rb:17:in 'Kernel#Integer': invalid value for Integer(): "12abc" (ArgumentError).

Kernel conversion functions

Besides Integer() and Float(), Kernel offers String(), Array(), Hash(), Rational() and Complex(). Array() is especially handy to accept "one or many" arguments.

Ruby String(), Array() and Hash()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Compare Array("one"), which yields ["one"], with "one".to_a, which does not exist. Array() never splits a string into lines or characters, and it turns nil into []. This makes the print_all pattern a cleaner alternative to items = [items] unless items.is_a?(Array). Array({ a: 1 }) gives [[:a, 1]] because it calls to_a.

Implicit conversions: to_str, to_ary, to_hash, to_proc

Some methods demand a particular type. "a" + x needs a string, [1] + x needs an array, **opts needs a hash, &obj needs a proc. Ruby does not call to_s for you in those places, because "count: " + 5 is almost always a mistake. Instead it calls the implicit conversion methods, which are named after the full type: to_str, to_ary, to_hash, to_proc, to_int, to_sym. Only objects that really are string-like, array-like and so on should define them.

Ruby Implicit conversion is strict (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The error is main.rb:1:in 'String#+': no implicit conversion of Integer into String (TypeError). The phrase "no implicit conversion" means Ruby looked for to_str on the integer and did not find it. The fix is explicit: "total: " + 5.to_s or, better, interpolation "total: #{5}".

When your own class defines the implicit method, the core library accepts it.

Ruby An object that converts implicitly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Path can be added to a string and passed where a file name is expected, because it provides to_str. Pair participates in destructuring (first, second = pair), in block parameters (|x, y|) and in flatten, because of to_ary. Doubler can follow the &, because &obj calls to_proc, and the same mechanism explains why &:upcase works: Symbol#to_proc builds a block that calls the method. Do not define the implicit methods lightly: once your object has to_ary, Ruby may treat it as an array in places you did not intend (for example puts would print its elements), and a method_missing that answers everything can trip these checks (method_missing and respond_to_missing?).

Which conversion does Ruby use where?

You write Ruby calls Notes
"#{x}", puts x to_s falls back to the default if it is not a String
p x, x.inspect inspect developer view
"a" + x to_str TypeError if missing
a, b = x, [x].flatten to_ary
f(**x) to_hash
map(&x) to_proc
[1,2,3][x] to_int float indexes are truncated through to_int
Array(x) to_ary, then to_a never raises for odd objects

Sorting out failures with the conversion methods

A good habit is to convert at the boundary: when data enters your program (input, files, JSON), convert it once with Integer(), Float(), Array() and friends, validate it, and from then on work with proper types. Inside your own classes, avoid to_s calls as a way to "make things work"; they hide type mistakes.

Ruby Converting input at the boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Using inspect in the error message shows exactly what was received, including the empty string and the stray spaces, which to_s would hide. Two conventions matter for your own classes: define to_s for the human view (and keep it stable if users depend on it), define inspect for the developer view (short, no secrets), and add implicit conversions only for types that truly are strings, arrays or hashes. Related reading: Strings, Symbols and Reading Input and Formatting Output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method does puts call on an object, and which does p call?

    puts prints the user-facing to_s form; p prints the debugging inspect form and returns its argument.
  2. 2. What does Integer("12abc") do?

    Kernel#Integer is strict and raises ArgumentError for invalid values. Add exception: false to get nil. The forgiving "12abc".to_i returns 12.
  3. 3. Why does "total: " + 5 raise a TypeError?

    String#+ calls to_str on its argument, and Integer has no to_str. You must convert explicitly with to_s or use interpolation.
  4. 4. Which method makes first, second = obj work for your own class?

    Multiple assignment, block parameter destructuring and flatten use the implicit to_ary method.
  5. 5. Why is a custom inspect useful for a class with a password field?

    The default inspect lists all instance variables. A custom inspect keeps sensitive data out of logs and debug output.

Summary

  • to_s is the user-facing text (used by puts and interpolation); inspect is the developer view (used by p, pp and error messages).
  • Define to_s to return a String, and inspect to show useful state while hiding secrets.
  • Explicit conversions (to_i, to_a, to_h) are forgiving; Integer(), Float(), Array() and String() are the strict or normalizing versions.
  • Implicit conversions (to_str, to_ary, to_hash, to_proc, to_int) are called by Ruby itself where a type is required.
  • A message such as "no implicit conversion of Integer into String" means the implicit method is missing.
  • Convert and validate input at the boundary of your program.

Next: Duck Typing and Polymorphism