为什么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 17:48:51
inspect
是一种默认情况下告诉你类名,实例的方法object_id
,并列出实例的实例变量。
print
并且puts
正如你所知道的那样使用对象to_s
方法的值STDOUT
。如Ruby的文档所示,Object#to_s
返回表示对象的字符串 - 用于最终用户的可读性。
print
并且puts
除了puts
自动附加换行符之外,它们是相同的,而print
不是。
https://stackoverflow.com/questions/-100003731
复制相似问题