Faruk Hossen
Faruk Hossen

Reputation: 185

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

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.

Upvotes: 0

Views: 67

Answers (1)

Adrian
Adrian

Reputation: 15171

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.

Upvotes: 3

Related Questions