【问题标题】:Why do `p` and `puts` give the same output? Are both calling `to_s`?为什么`p`和`puts`给出相同的输出?都在调用 `to_s` 吗?
【发布时间】:2015-11-17 04:24:47
【问题描述】:

在以下代码中,pputs 给出相同的输出。

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

为什么会这样? p 应该调用 book1.inspect 而不是 book1.to_s

【问题讨论】:

  • 我无法重现您描述的行为。 Ruby 2.2.3 的行为与预期一样,p 执行 inspectputs 执行 to_s。 (虽然我不得不取消注释 to_s 实现......)
  • 我使用的是 ruby​​ 1.9.3
  • @Abs 该链接并没有真正为这个问题提供任何答案
  • 我不小心标记了这个

标签: ruby ruby-1.9


【解决方案1】:

在 ruby​​ 1.9 中,inspect 的默认行为是调用 to_s。这在以后的版本中发生了变化。如果您想要不同的输出,您可能需要覆盖 inspectto_s,或者只是升级您的 ruby​​ 版本。

请看这里:http://ruby-doc.org/core-1.9.3/Object.html#method-i-inspect

如果没有被覆盖,使用 to_s 方法生成字符串。

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 2015-11-19
    • 2019-12-17
    • 2016-09-03
    • 2015-05-05
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多