views:

1057

answers:

1

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

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

The first array is printed inline because it fits within the column width prettyprint allows (79 characters)... the second is split onto multiple lines, because it does not. But I can find no method for changing the column that this behavior starts on.

pp depends on PrettyPrint (which has ways to allow different widths for the buffer). Is there any way to change the default column width for pp, without rewriting it from scratch (accessing PrettyPrint directly)?

Alternately, is there a similar ruby gem that provides this functionality?

+3  A: 
#!/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"]
Wayne Conrad