gpt4 book ai didi

ruby - 为什么这个 Ruby 对象同时具有 to_s 和 inspect 方法,它们看起来做同样的事情?

转载 作者:数据小太阳 更新时间:2023-10-29 06:20:10 25 4
gpt4 key购买 nike

为什么这个 Ruby 对象的 to_sinspect 方法看起来做同样的事情?

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_sinspect 有什么区别?
  • putsprintp 之间有什么区别?

如果我注释掉 to_sinspect 函数,我会得到如下结果。

#<Graph:0x100124b88>
#<Graph:0x100124b88>

最佳答案

inspect 更多地用于调试,to_s 用于最终用户或显示目的。

例如,[1,2,3].to_s[1,2,3].inspect 产生不同的输出。

关于ruby - 为什么这个 Ruby 对象同时具有 to_s 和 inspect 方法,它们看起来做同样的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2625667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com