【问题标题】:Customizing IRB output自定义 IRB 输出
【发布时间】:2012-06-27 13:40:53
【问题描述】:

我创建了一个名为 SpecialArray 的类,我想自定义 irb 显示的输出类型。目前,当我创建类的新实例时,irb 返回整个对象。这是我目前看到的:

1.9.3p194 :022 > SpecialArray.new([1,2,0,6,2,11]) 
=> #<UniqueArray:0x007ff05b026ec8 @input=[1, 2, 0, 6, 2, 11], @output=[1, 2, 0, 6, 11]>

但我只想显示我定义为输出的内容。换句话说,我想看看这个。

1.9.3p194 :022 > SpecialArray.new([1,2,0,6,2,11]) 
=> [1, 2, 0, 6, 11]

我需要做什么来指定 irb 应该只显示输出?

解决方案:

这是我最终创建的方法。

def inspect
  output.inspect
end

【问题讨论】:

    标签: ruby irb inspect


    【解决方案1】:

    IRB 调用Object#inspect 方法来获取对象的字符串表示形式。您只需要像这样覆盖此方法:

    class Foo
      def inspect
        "foo:#{object_id}"
      end
    end
    

    然后在 IRB 中你会得到:

    >> Foo.new
    => foo:70250368430260 
    

    在您的特定情况下,只需让 SpecialArray#inspect 返回底层数组的字符串表示形式,例如:

    SpecialArray
      def inspect
        @output.inspect
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2016-03-03
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 2010-09-14
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多