2.3 Displaying Objects: puts and p, to_s and inspect

puts and p

The difference between these methods are better explained through an example:
Example Code:

Output Window

puts generally prints the result of applying to_s on an object while p prints the result of inspecting the object.

inspect vs to_s

Yet another example:
Example Code:

Output Window

As you can see, puts prints the class name of the object along with a number displayed as hex. The number is relative to the position of the object in memory, but we seldom find any use for it.

p on the other hand prints the class name and all the instance variables of the object. This can be very useful while debugging.

The above example illustrated the default behaviour of p and puts. But there will be occasions when you'd want to customize what these methods display. This is easily done by overriding the to_s method.

In the following exercise, override the to_s method of the Item class so that it returns a string with both the item's name and quantity.

Output Window

Did you notice that the output of both p and puts became the same in the above example? This is because if you override to_s for an object, Ruby will treat it as the result of inspect as well, unless you override inspect separately. This is typically the desired behaviour, but you can implement inspect yourself if you need different results for each method.

Also, it is generally a best practice to override the to_s method in your classes so that it can return meaningful result that is tailored for each class.

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2024 by Jasim A Basheer