2010-01-21 47 views
40

是否可以在格式化輸出時更改相紙(require 'pp')使用的寬度?例如:格式化Ruby的相紙

"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)?

或者,是否有類似的紅寶石提供此功能?

回答

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

4

找到 「AP」 又名 「Awesome_Print」 有用的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 
從第

O/P VS 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 
    } 
] 

參考:

+0

這是有趣的附加信息。然而,這並不是真正的問題的答案,根據OP的要求,「四十」,「兩個」應該在一條線上。另外,我認爲對於任何值得考慮使用哪個的人來說,值得注意的是這裏顯示的'ap'輸出不能被ruby eval讀回(特別是因爲數組索引被顯示的方式),' pp「的輸出可能會很頻繁(它只會改變基本對象類型的空白 - 雖然時間對象清楚地顯示了一個例外)。只是思考的食物。 – lindes 2017-12-02 19:35:59