Formatting Ruby's prettyprint

前端 未结 2 568
时光取名叫无心
时光取名叫无心 2021-02-01 13:09

Is it possible to change the width that prettyprint (require \'pp\') uses when formatting output? For example:

\"mooth\"=>[\"booth\", \"month\",          


        
相关标签:
2条回答
  • 2021-02-01 13:34

    Found "ap" aka "Awesome_Print" useful as well from git-repo

    Code used to test pp and 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
    

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

    Reference:

    • Stackoverflow posting
    • Web citing
    0 讨论(0)
  • 2021-02-01 13:44
    #!/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"]
    

    To change the default with a monkey patch:

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

    These methods also work in MRI 1.9.3

    0 讨论(0)
提交回复
热议问题