格式化输出时,是否可以更改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的prettyprint,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2112016/

10-11 15:36