代码之家  ›  专栏  ›  技术社区  ›  Myrddin Emrys

格式化Ruby的预打印

  •  44
  • Myrddin Emrys  · 技术社区  · 15 年前

    可以更改预打印的宽度吗( require 'pp' )格式化输出时使用?例如:

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

    第一个数组以内联方式打印,因为它符合列宽预打印允许(79个字符)…第二行被拆分为多行,因为它没有。但我找不到任何方法来更改此行为开始的列。

    pp 取决于 PrettyPrint (它可以为缓冲区提供不同的宽度)。有什么方法可以更改的默认列宽吗 聚丙烯 ,无需从头重写(访问 精美印刷品 直接)?

    或者,是否有类似的Ruby Gem提供此功能?

    2 回复  |  直到 9 年前
        1
  •  55
  •   Wayne Conrad    12 年前
    #!/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"]
    

    要使用monkey补丁更改默认值,请执行以下操作:

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

        2
  •  5
  •   Abhijeet    8 年前

    发现“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
    

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

    参考文献: