Forum: Ruby How to capture PrettyPrint output to string?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
List R. (Guest)
on 2005-12-08 04:53
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!
leavengood (Guest)
on 2005-12-08 05:05
(Received via mailing list)
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
nobuyoshi.nakada (Guest)
on 2005-12-08 05:13
(Received via mailing list)
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, "")
gsinclair (Guest)
on 2005-12-08 05:41
(Received via mailing list)
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
ara.t.howard (Guest)
on 2005-12-08 05:45
(Received via mailing list)
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 = ""

;-)

-a
This topic is locked and can not be replied to.