How to capture PrettyPrint output to string?

I’d like to capture the output of pp (PrettyPrint) as a string, as
opposed to putting it on stdout.

Something like:
dump = myvar.pp

dump.class # => String

(Using .pretty_print_inspect is not adequate, as it’s not the same as
pp, has no newlines, etc.)

Thanks!

require ‘pp’
require ‘stringio’

def my_pp(*args)
old_out = $stdout
begin
s=StringIO.new
$stdout=s
pp(*args)
ensure
$stdout=old_out
end
s.string
end

Hi,

At Thu, 8 Dec 2005 11:54:04 +0900,
List R. wrote in [ruby-talk:169485]:

I’d like to capture the output of pp (PrettyPrint) as a string, as
opposed to putting it on stdout.

dump = PP.pp(myvar, “”)

List R. wrote:

I’d like to capture the output of pp (PrettyPrint) as a string, as
opposed to putting it on stdout.

Something like:
dump = myvar.pp

http://extensions.rubyforge.org defines Object#pp_s which does what you
want. You can examine the implementation on the website.

The Facets/Core project may have something similar. Hopefully with a
nicer name!

This functionality is a screaming omission from the standard library!

Gavin

On Thu, 8 Dec 2005, nobuyoshi nakada wrote:

Hi,

At Thu, 8 Dec 2005 11:54:04 +0900,
List R. wrote in [ruby-talk:169485]:

I’d like to capture the output of pp (PrettyPrint) as a string, as
opposed to putting it on stdout.

dump = PP.pp(myvar, “”)

i usually use

PP.pp myvar, dump = “”

:wink:

-a