【发布时间】:2011-02-07 05:08:30
【问题描述】:
为什么这个 Ruby 对象同时包含看起来做同样事情的 to_s 和 inspect 方法?
p 方法调用 inspect 和 puts/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_s和inspect有什么区别? -
puts、print和p之间有什么区别?
如果我注释掉 to_s 或 inspect 函数,我会得到如下结果。
#<Graph:0x100124b88>
#<Graph:0x100124b88>
【问题讨论】: