为什么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
为什么Ruby有两个功能做同样的事情?to_s
和inspect之间有什么区别?
发布于 2018-03-27 17:47:54
inspect
是一种默认情况下告诉你类名与实例的方法object_id
,并列出实例的实例变量。
print
和puts
正如你所知道的那样,使用对象to_s
方法的值STDOUT
。
如Ruby的文档所示,Object#to_s
返回表示对象的字符串 。
print
和puts
除了puts
自动附加换行符之外,它们是相同的,而print
不是。
https://stackoverflow.com/questions/-100004316
复制相似问题