Myr*_*rys 43 ruby pretty-print
是否可以更改prettyprint(require 'pp')在格式化输出时使用的宽度?例如:
"mooth"=>["booth", "month", "mooch", "morth", "mouth", "mowth", "sooth", "tooth"]
"morth"=>["forth",
"mirth",
"month",
"mooth",
"morph",
"mouth",
"mowth",
"north",
"worth"]
Run Code Online (Sandbox Code Playgroud)
第一个数组是内联打印的,因为它适合列宽,prettyprint允许(79个字符)...第二个数组分成多行,因为它没有.但我找不到更改此行为开始的列的方法.
pp取决于PrettyPrint(有哪些方法允许缓冲区的不同宽度).有没有办法更改默认列宽pp,而无需从头开始重写(PrettyPrint直接访问)?
或者,是否有类似的ruby gem提供此功能?
Way*_*rad 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"]
Run Code Online (Sandbox Code Playgroud)
要使用猴子补丁更改默认值:
#!/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"]
Run Code Online (Sandbox Code Playgroud)
这些方法也适用于MRI 1.9.3
从git-repo中发现"ap"又名"Awesome_Print"也很有用
用于测试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
Run Code Online (Sandbox Code Playgroud)
来自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
}
]
Run Code Online (Sandbox Code Playgroud)
参考: