简体   繁体   中英

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM