【问题标题】:How to stop class initializer from printing object in Ruby?如何阻止类初始化程序在 Ruby 中打印对象?
【发布时间】:2016-01-10 18:30:23
【问题描述】:

每当我从 IRB 实例化一个新方法时,它都会打印一堆我认为没有必要的东西。这是预期的行为吗?我可以阻止它发生吗?

比如下面的代码

class Box
  def initialize(index)
    @index = index
  end
end

box = Box.new(5)

将打印

 #<Box:0x000000015836e8 @index=5>

有了更复杂的东西,我的终端会得到更多。

【问题讨论】:

    标签: ruby output irb


    【解决方案1】:

    这是意料之中的,因为默认情况下irb 会打印出最新评估的结果。

    您可以use noecho 或附加;nil 以打印出nil

    box = Box.new(5); nil
    

    【讨论】:

    • 没有 irb 打印这些东西有点违背了 REPL 的目的。
    【解决方案2】:

    这是预期的行为。 irb 是REPL(读取、评估、打印循环)。这意味着它将打印计算您输入的每个连续表达式的结果。调用类的构造函数的结果是新对象。分配的结果就是被分配的任何东西。

    您可以覆盖类的Object#inspect 方法来更改正在打印的内容:

    class Box
      def initialize(index)
        @index = index
      end
    
      def inspect
        "A box with index #{@index}"
      end
    end
    
    box = Box.new(5)
    
    # => >A box with index 5
    

    【讨论】:

    • 在 Ruby 2.3.0 中我得到(Object doesn't support #inspect)
    • Nvm,是因为我把inspect方法放在private下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多