4

Possible Duplicate:
Why do this Ruby object have two to_s and inspect methods that do the same thing? Or, so it seems

In Ruby: If x is some variable, is there a difference between using x.inspect and using x.to_s? What is the difference between the 2 methods?

Community
  • 1
  • 1
user1452463
  • 119
  • 1
  • 2
  • 9

1 Answers1

7

They are usually but not always the same. According to the documentation for Object.inspect():

If not overridden, uses the to_s method to generate the string.

So by default, they return the same thing because inspect() calls to_s(). Sometimes, however, it makes sense to override to_s() to do one thing, but when inspecting an object from irb, you want to see more details. So they can be set up to do different things.

Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
  • 1
    This is no longer the case, as of ruby 2.1.1 (at least, haven't checked backwards) `inspect` does not call `to_s` by default. https://ruby-doc.org/core-2.1.1/Object.html#method-i-inspect – Paulo Casaretto Mar 31 '17 at 12:38
  • 1
    @PauloCasaretto The 2.1.1 source code shows that for non-compound objects that don't override `inspect()`, Ruby will call `rb_any_to_s` on the object. So the documentation is worded differently, and the C implementation has been modified, but the behavior remains the same as I've described here. (For compound objects, `inspect()` is called until recursing to an object with an overridden `inspect()` or a non-compound object, just as before.) – Darshan Rivka Whittle Mar 31 '17 at 20:39