Putting the results of pp (or anything outputted to console) into a string

前端 未结 4 590
心在旅途
心在旅途 2020-12-09 15:00

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 p

4条回答
  •  天涯浪人
    2020-12-09 15:28

    This is a nice 'n simple way to capture the output of pp:

    require 'pp'
    
    asdf = {'a' => 1, :b => 2, 'c' => %w[ho daddy]}
    foo = PP.pp(asdf, '')
    puts foo
    => {"a"=>1, :b=>2, "c"=>["ho", "daddy"]}
    

    Capturing STDOUT, which is the default channel used by puts and print and that things like pp piggyback on, is a bit more complex:

    require 'pp'
    require 'stringio'
    
    asdf = {'a' => 1, :b => 2, 'c' => %w[ho daddy]}
    puts 'Writing to STDOUT...'
    pp asdf
    
    # remember the old STDOUT stream...
    old_stdout = $stdout
    
    # ...and create a new stream that writes to a string.
    captured_stdio = StringIO.new('', 'w')
    $stdout = captured_stdio
    
    # This is all captured...
    puts 'Capturing to buffer...'
    pp asdf
    
    # reset STDOUT
    $stdout = old_stdout
    puts 'Capturing off...'
    
    # show what we got...
    puts captured_stdio.string
    

    And what was printed:

    Writing to STDOUT...
    {"a"=>1, :b=>2, "c"=>["ho", "daddy"]}
    Capturing off...
    Capturing to buffer...
    {"a"=>1, :b=>2, "c"=>["ho", "daddy"]}
    

    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 to captured_stdio.

提交回复
热议问题