下面是一个简单的图形节点:
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
可以做到这一点,但它没有。)
发布于 2017-03-03 14:22:38
您要查找的内容(以pry/irb格式输出的内容)是Object#inspect
的结果,因此只需针对Node
使用alias_method
alias_method :inspect, :to_s
如果您已经重新定义了Node#to_s
,或者只是:
def inspect
"<#{value} #{children.collect(&:value)}>"
end
此外,请确保您没有安装awesome_print
gem。
https://stackoverflow.com/questions/42581245
复制