为什么这个Ruby对象既有to_s个方法,又有inspect个方法,它们似乎做了同样的事情?

p方法调用inspect,put/print调用to_s来表示对象.

如果我跑

class Graph
  def initialize
    @nodeArray = Array.new
    @wireArray = Array.new
  end
  def to_s # called with print / puts
    "Graph : #{@nodeArray.size}"
  end
  def inspect # called with p
    "G"
  end
end

if __FILE__ == $0
  gr = Graph.new
  p gr
  print gr
  puts gr
end

我明白了

G
Graph : 0
Graph : 0
  • 那么,为什么Ruby有两个函数做同样的事情呢?to_sinspect之间有什么区别?
  • putsprintp之间有什么区别?

If I comment out the to_s or inspect function, 我明白了 as follows.

#<Graph:0x100124b88>
#<Graph:0x100124b88>

推荐答案

inspect更多用于调试,to_s更多用于最终用户或显示目的.

例如,[1,2,3].to_s[1,2,3].inspect产生不同的输出.

Ruby相关问答推荐

Ruby 扁平化 JSON 对象或哈希

指南针手表:未定义的方法存在吗?对于文件:类

Ruby:如何在 vanilla ruby​​ 中使用有效支持日期?

使用正则表达式判断用户输入的开头是否正好有两个大括号

如何判断 Ruby 文件是否为空?

为什么在 Ruby 中将 0 视为 True?

在 Ruby 中为类添加实例变量

如何在新行之间拆分字符串并保留空白行?

Ruby:将unix时间戳转换为日期

osx bash上的树命令

来自 Linux 上的命令队列的并行处理(bash、python、ruby ......随便)

如何合并散列数组以获取值数组的散列

Vagrant - 如何拥有特定于主机平台的配置步骤

RSpec allow/expec vs expect/and_return

如何强制 Ruby 字符串为 n 个字符

在 Ruby 中获取本月的最后一天

Python 中的一切都像 Ruby 一样是对象吗?

相当于 Ruby 的 cURL?

如何在 Rails 应用程序中使用 httparty 的基本身份验证?

如何使用 Ruby 删除回车?