Why do this Ruby object have both to_s and inspect methods that appear to do the same thing? Why do this Ruby object have both to_s and inspect methods that appear to do the same thing? ruby ruby

Why do this Ruby object have both to_s and inspect methods that appear to do the same thing?


inspect is used more for debugging and to_s for end-user or display purposes.

For example, [1,2,3].to_s and [1,2,3].inspect produce different output.


inspect is a method that, by default, tells you the class name, the instance's object_id, and lists off the instance's instance variables.

print and puts are used, as you already know, to put the value of the object's to_s method to STDOUT. As indicated by Ruby's documentation, Object#to_s returns a string representing the object -- used for end-user readability.

print and puts are identical to each other except for puts automatically appends a newline, while print does not.


To compare with Python, to_s is like __str__ and inspect is like __repr__. to_s gives you a string, whereas inspect gives you the string representation of the object. You can use the latter to construct an object if you wish.