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:
class Item
class Item
  def inspect
    "Result of inspect"
  end
end
 
puts Item.new
puts Item.new.to_s
p Item.new
 
 
 
 

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:
class Item
class Item
  def initialize(item_name, qty)
    @item_name = item_name
    @qty = qty
  end
end
 
item = Item.new("a",1)
 
puts item
p item
 
 
 
 

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.

class Item
class Item
  def initialize(item_name, qty)
    @item_name = item_name
    @qty = qty
  end
  
    # override 'to_s' here  
end
 
item = Item.new("a",1)
 
puts item
p item
 
 
 

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-2025 by Jasim A Basheer