为什么这个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_s
和inspect
之间有什么区别? -
puts
、print
和p
之间有什么区别?
If I comment out the to_s
or inspect
function, 我明白了 as follows.
#<Graph:0x100124b88>
#<Graph:0x100124b88>