为什么Ruby里对象to_s
和inspect
方法看起来做同样的事情?
p
方法调用inspect
并输出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
to_s
和inspect之间有什么区别?发布于 2018-03-28 16:21:38
inspect
更多地用于调试,to_s
最终用户或显示目的。
例如,[1,2,3].to_s
并[1,2,3].inspect
产生不同的输出。
https://stackoverflow.com/questions/-100003731
复制相似问题