47

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

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

第一个数组是内联打印的,因为它适合漂亮打印允许的列宽(79 个字符)……第二个数组被分成多行,因为它没有。但是我找不到更改此行为开始的列的方法。

pp取决于PrettyPrint(它有办法允许缓冲区有不同的宽度)。有什么方法可以更改 的默认列宽pp,而无需从头开始重写(PrettyPrint直接访问)?

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

4

2 回答 2

61
#!/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

于 2010-01-21T19:18:19.910 回答
7

从git-repo发现“ap”又名“Awesome_Print”也很有用

用于测试pp和ap的代码:

require 'pp'
require "awesome_print" #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 与 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
    }
]

参考:

于 2015-09-29T14:51:33.837 回答