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.
In ruby 1.9, the default behavior of
inspectis to callto_s. This changed in later versions. You might have to overrideinspectas well asto_sif 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