在 irb (ruby) 中截断 #inspect 输出 [英] Truncate #inspect output in irb (ruby)

查看:39
本文介绍了在 irb (ruby) 中截断 #inspect 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to truncate #inspect output in irb (a large output must be cropped to MAX_LEN).

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

Currently, I override :inspect, :to_s methods for all specific objects.

还有其他解决办法吗?

  • 改变 $stdout 吗?
  • 其他?

推荐答案

对于干净的解决方案,gem install hirb.hirb 页面 irb 的返回值如果太长.

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

如果你想对 irb 进行猴子补丁:

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

我不建议这样做,因为它是一种黑客行为,并且会在需要 ap 和 hirb 等 gem 时破坏.

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

我建议尝试 ripl,而不是猴子补丁 irb,这是一种旨在扩展的 irb 替代方案.以上作为 ripl 插件将是:

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

使用此插件,您可以根据需要使用它,或者如果您想始终使用它,请将其添加到您的 ~/.riplrc 中.

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

这篇关于在 irb (ruby) 中截断 #inspect 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆