是否可以更改prettyprint(require 'pp')在格式化输出时使用的宽度?例如:

"mooth"=>["booth", "month", "mooch", "morth", "mouth", "mowth", "sooth", "tooth"]
"morth"=>["forth",
 "mirth",
 "month",
 "mooth",
 "morph",
 "mouth",
 "mowth",
 "north",
 "worth"]

第一个数组是内联打印的,因为它符合prettyprint允许的列宽(79个字符)...第二行被拆分为多行,因为它没有.但我找不到任何方法来更改此行为开始的列.

pp取决于PrettyPrint(它有允许缓冲区不同宽度的方法).有没有办法将默认列宽更改为pp,而不必从头重写(直接访问PrettyPrint)?

或者,是否有类似的ruby gem提供此功能?

推荐答案

#!/usr/bin/ruby1.8

require 'pp'
mooth = [
  "booth", "month", "mooch", "morth",
  "mouth", "mowth", "sooth", "tooth"
]
PP.pp(mooth, $>, 40)
# => ["booth",
# =>  "month",
# =>  "mooch",
# =>  "morth",
# =>  "mouth",
# =>  "mowth",
# =>  "sooth",
# =>  "tooth"]
PP.pp(mooth, $>, 79)
# => ["booth", "month", "mooch", "morth", "mouth", "mowth", "sooth", "tooth"]

要使用猴子补丁更改默认设置,请执行以下操作:

#!/usr/bin/ruby1.8

require 'pp'

class PP
  class << self
    alias_method :old_pp, :pp
    def pp(obj, out = $>, width = 40)
      old_pp(obj, out, width)
    end
  end
end

mooth = ["booth", "month", "mooch", "morth", "mouth", "mowth", "sooth", "tooth"]
pp(mooth)
# => ["booth",
# =>  "month",
# =>  "mooch",
# =>  "morth",
# =>  "mouth",
# =>  "mowth",
# =>  "sooth",
# =>  "tooth"]

这些方法也适用于MRI 1.9.3

Ruby相关问答推荐

Ruby脚本递归地创建深度嵌套的目录

每次调用返回新的 REST 响应的 Ruby Rspec class_double

Ruby中带和不带下划线_的方法参数有什么区别

为什么 Rake 不能连续调用多个任务?

在 Ruby 中为类添加实例变量

从href html标签中提取带有Ruby中nokogiri的链接(URL)?

Ruby 在与源相同的目录中加载配置(yaml)文件

复制文件,在 Ruby 中根据需要创建目录

在 Ubuntu 上安装 Ruby 1.9.1?

判断 Ruby HTTP 响应是否成功

Ruby 运算符优先级表

如何引用全局变量和类变量?

与 String 相比,在 Ruby 中使用 StringIO 有哪些优势?

获取Ruby中数组的差异

Ruby中的常量或类变量?

如何在 ruby​​ net/http 中实现 cookie 支持?

在 ruby​​ 异常中捕获行号

如何在没有 Rails 的情况下使用 RSpec?

如何使用 Nokogiri 删除 node ?

使用哈希值呈现 ERB 模板