Why do `p` and `puts` give the same output? Are both calling `to_s`?

67 Views Asked by At

In the following code, p and puts give the same output.

class Book
  def initialize(title, price)
    @title = title
    @price = price
  end  
  def to_s
    "book with title=#{@title} and price=#{@price}"
  end
end

book1 = Book.new("Book of Ruby", 50.63)
puts book1 # => book with title=Book of Ruby and price=50.63
p book1    # => book with title=Book of Ruby and price=50.63

Why is this the case? p should have called book1.inspect instead of book1.to_s.

1

There are 1 best solutions below

0
Adrian On BEST ANSWER

In ruby 1.9, the default behavior of inspect is to call to_s. This changed in later versions. You might have to override inspect as well as to_s if you want different output, or just upgrade your ruby version.

See here: http://ruby-doc.org/core-1.9.3/Object.html#method-i-inspect

If not overridden, uses the to_s method to generate the string.