格式化Ruby的相纸

格式化输出时,是否可以改变相纸的宽度(require'pp require 'pp' )? 例如:

 "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提供这种function?

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

发现“ap”aka“Awesome_Print”也很有用,从git-repo

用于testingpp和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 

O / P从PP与AP:

 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 } ] 

参考:

  • Stackoverflow张贴
  • networking引用