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

前端 未结 4 598
心在旅途
心在旅途 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:36

    If you want to save the output into a string, you can use stringio

    Here is an example:

    #!/usr/bin/env ruby
    
    require 'stringio'
    require 'pp'
    
    def output_to_string
      sio = StringIO.new
      old_stdout, $stdout = $stdout, sio
      yield
      $stdout = old_stdout # restore stdout
      sio.string
    end
    
    result = output_to_string do
      puts "hello"
      pp ["value1", "value2", "value3"]
    end
    
    puts "result: #{result}"
    

    If you exec this code you get:

    result: hello
    ["value1", "value2", "value3"]
    

提交回复
热议问题