user1452463 user1452463 - 2 months ago 8
Ruby Question

Difference between x.inspect and x.to_s in Ruby?


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?

Answer

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.