【发布时间】:2017-03-03 14:19:32
【问题描述】:
这是一个简单的图形节点:
Node = Struct.new(:value, :children) do
def initialize(value, children=[]); super; end
end
我经常想在pry 或irb 控制台中查看此内容。问题是,当我连接图表并查看一个节点时,我得到如下输出:
[1] pry(main)> node
=> #<struct Node
value=13,
children=
[#<struct Node
value=23,
children=
[#<struct Node:...>,
#<struct Node
value=19,
children=[#<struct Node:...>, #<struct Node value=10, children=[#<struct Node:...>]>]>]>,
#<struct Node value=28, children=[#<struct Node:...>]>,
#<struct Node value=2, children=[#<struct Node:...>]>,
#<struct Node value=14, children=[#<struct Node:...>]>]>
等等
这很快就会失控并且难以阅读。我可以在 Node 上定义一个更易读的to_s:
def to_s; "<#{value} #{children.collect(&:value)}>"; end
但我仍然需要致电puts node 才能看到:
[1] pry(main)> puts node
<13 [23, 28, 2, 14]>
=> nil
只需在控制台中输入 node 即可得到原始的详细输出(pry 和 irb)。每次我想在调试器中查看更紧凑的node 表示时,输入puts 很烦人。
我可以定义一些方法来覆盖对象的控制台显示值吗? (我认为覆盖 inspect 会这样做,但事实并非如此。)
【问题讨论】: