Why do this Ruby object have both to_s and inspect methods that appear to do the same thing?
Why do this Ruby object both a to_s
and inspect
methods that appear to do the same thing?
The p
method calls inspect
and puts/print calls to_s
for representing the object.
If I run
class Graph
def initialize
@nodeArray = Array.new
@wireArray = Array.new
end
def to_s # called with print / puts
"Graph : #{@nodeArray.size}"
end
def inspect # called with p
"G"
end
end
if __FILE__ == $0
gr = Graph.new
p gr
print gr
puts gr
end
I get
G
Graph : 0
Graph : 0
- Then, why does Ruby have two functions do the same thing? What is the difference between
to_s
andinspect
? - And what's the difference between
puts
,print
, andp
?
If I comment out the to_s
or inspect
function, I get as follows.
#<Graph:0x100124b88>
#<Graph:0x100124b88>
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.
Further, there is a to_str
method on certain objects, which you would call when you need a String-like object, and not just a string representation. (Try in IRB: [1,2,3].to_str
and it will fail, yet [1,2,3].to_s
will not.) I feel I should mention this because I've been bitten by it before :)
For anyone arriving here after starting out with Ruby Koans, a simple example of where to_s
and inspect
differ in output is this:
nil.to_s # will yield an empty string, ie ""
nil.inspect # will yield the string "nil"