在格式化输出时是否可以更改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提供此功能?
答案 0 :(得分:55)
#!/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
答案 1 :(得分:5)
发现&#34; ap&#34;又名&#34; Awesome_Print&#34;来自git-repo
也很有用用于测试pp和ap的代码:
require 'pp'
require 'ap' #requires gem install awesome_print
data = [false, 42, %w{fourty two}, {:now => Time.now, :class => Time.now.class, :distance => 42e42}]
puts "Data displayed using pp command"
pp data
puts "Data displayed using ap command"
ap data
来自pp vs ap的O / P:
Data displayed using pp command
[false,
42,
["fourty", "two"],
{:now=>2015-09-29 22:39:13 +0800, :class=>Time, :distance=>4.2e+43}]
Data displayed using ap command
[
[0] false,
[1] 42,
[2] [
[0] "fourty",
[1] "two"
],
[3] {
:now => 2015-09-29 22:39:13 +0800,
:class => Time < Object,
:distance => 4.2e+43
}
]
参考: