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.
Ccfe7d097475a32dc3ff78d6fc42c852?d=identicon&s=25 List Recv (lstrecv)
on 2005-12-08 03: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!
4b174722d1b1a4bbd9672e1ab50c30a9?d=identicon&s=25 leavengood (Guest)
on 2005-12-08 04: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
04a56914cc09f0858d3fca2bf4cbde34?d=identicon&s=25 nobuyoshi.nakada (Guest)
on 2005-12-08 04:13
(Received via mailing list)
Hi,

At Thu, 8 Dec 2005 11:54:04 +0900,
List Recv 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, "")
Bfcc9047bea80035a936648dc1912ec4?d=identicon&s=25 gsinclair (Guest)
on 2005-12-08 04:41
(Received via mailing list)
List Recv 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
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 ara.t.howard (Guest)
on 2005-12-08 04:45
(Received via mailing list)
On Thu, 8 Dec 2005, nobuyoshi nakada wrote:

> Hi,
>
> At Thu, 8 Dec 2005 11:54:04 +0900,
> List Recv 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.