在irb(ruby)中截断#inspect输出

Pav*_*lov 3 ruby stdout irb inspect

我想在irb中截断#inspect输出(必须将大输出裁剪为MAX_LEN).

目前,我为所有特定对象覆盖:inspect,:to_s方法.

还有其他解决方案吗?

  • 改变$ stdout?
  • 其他?

cld*_*ker 5

For a clean solution, gem install hirb. hirb pages irb's returned values if they get too long.

If you want to monkeypatch irb:

module IRB
  class Irb
    def output_value
     @context.last_value.to_s.slice(0, MAX_LEN)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

I don't recommend this because it's a hack and breaks any time gems like ap and hirb are required.

Instead of monkeypatching irb, I'd recommend trying ripl, an irb alternative that is meant to extended. The above as a ripl plugin would be:

require 'ripl'
module Ripl::SlicedInspect
  def format_result(result)
    result_prompt + result.inspect.slice(MAX_LEN)
  end
end
Ripl::Shell.send :include, Ripl::SlicedInspect
Run Code Online (Sandbox Code Playgroud)

With this plugin, you could require it as needed or add to your ~/.riplrc if you want to always use it.