【问题标题】:How can I change the pry/irb console display value for a Ruby object?如何更改 Ruby 对象的 pry/irb 控制台显示值?
【发布时间】:2017-03-03 14:19:32
【问题描述】:

这是一个简单的图形节点:

Node = Struct.new(:value, :children) do
  def initialize(value, children=[]); super; end
end

我经常想在pryirb 控制台中查看此内容。问题是,当我连接图表并查看一个节点时,我得到如下输出:

[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 即可得到原始的详细输出(pryirb)。每次我想在调试器中查看更紧凑的node 表示时,输入puts 很烦人。

我可以定义一些方法来覆盖对象的控制台显示值吗? (我认为覆盖 inspect 会这样做,但事实并非如此。)

【问题讨论】:

    标签: ruby console irb pry


    【解决方案1】:

    您要查找的内容(在 pry/irb 中输出的内容)是 Object#inspect 的结果,因此只需将 alias_method 替换为 Node

    alias_method :inspect, :to_s
    

    如果您已经重新定义了Node#to_s,或者只是:

    def inspect
      "<#{value} #{children.collect(&:value)}>"
    end
    

    另外,请确保您没有安装 awesome_print gem。

    【讨论】:

    • 定义inspect 对控制台中打印的内容没有影响(除非我使用puts node,这是我试图避免的)。我确实安装了awesome_print,但它没有加载到有问题的脚本中,所以如果这是导致问题的原因,我会感到惊讶。
    • awesome_print 正在由pry 加载,它会在所有对象上修补inspect
    • 有趣。 irb 也在做同样的事情吗?我在那里得到相同的结果。我真的不想卸载 awesome_print — 关于如何处理这个问题的任何建议?
    • 是的。如果您确实想使用awesome_print,请使用puts node;如果您只想使用node,请卸载awesome_print。没有灵丹妙药。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多