INSPECTING OBJECTS
Incidentally, notice too that I have ‘looked inside’ the Treasure object, t1, using the inspect method:
t1.inspect
The inspect method is defined for all Ruby objects. It returns a string containing a human-readable representation of the object. In the present case, it displays something like this:
#
This begins with the class name, Treasure; the name is followed by a number, which may be different from the number shown above – this is Ruby’s internal identification code for this particular object; then there are the names and values of the object’s variables.
Ruby also provides the p method as a shortcut to inspecting objects and printing out their details, like this:
p( anobject )
To see how to_s can be used with a variety of objects and to test how a Treasure object would be converted to a string in the absence of an overridden to_s method, try out the 8to_s.rb program.
puts(Class.to_s) #=> Class
puts(Object.to_s) #=> Object
puts(String.to_s) #=> String
puts(100.to_s) #=> 100
puts(Treasure.to_s) #=> Treasure