We know
require 'pp'
a=["value1", "value2", "value3"]
pp a
pretty prints the array as an output to the console. How do I get that pretty output into a string (a string containing the newlines that makes things pretty, etc.)?
...purpose being to return that pretty string from a method.
#pretty_inspect
also comes along when you first require 'pp' - See: http://ruby-doc.org/stdlib-2.1.0/libdoc/pp/rdoc/Kernel.html#method-i-pretty_inspectIf you want the version that is outputted to the
irb
console that isand doesn't have any requires necessary.
Another way to use stringio, without changing $stdout:
This is a nice 'n simple way to capture the output of
pp
:Capturing STDOUT, which is the default channel used by
puts
andprint
and that things likepp
piggyback on, is a bit more complex:And what was printed:
The last two lines above were stored in
captured_stdio
by substituting that for the normal$stdout
channel. Anything written to (what would be STDOUT) got stored. Swapping back in the original channel restored normal printing, and stopped anything else from being written tocaptured_stdio
.If you want to save the output into a string, you can use
stringio
Here is an example:
If you exec this code you get: