script_kiddie script_kiddie - 25 days ago 6x
Ruby Question

How can I capture STDOUT to a string?

puts "hi"
puts "bye"

I want to store the STDOUT of the code so far (in this case hi \nbye into a variable say 'result' and print it )

puts result

The reason I am doing this is I have integrate an R code into my Ruby code, output of which is given to the STDOUT as the R code runs , but the ouput cannot be accessed inside the code to do some evaluations. Sorry if this is confusing. So the "puts result" line should give me hi and bye.


Redirect Standard Output to a StringIO Object

I'm not sure this is useful, but you can certainly redirect standard output to a variable. For example:

# Set up standard output as a StringIO object.
foo =
$stdout = foo

# Send some text to $stdout.
puts 'hi'
puts 'bye'

# Access the data written to standard output.
# => "hi\nbye\n"

# Send your captured output to the original output stream.
STDOUT.puts $stdout.string

In practice, this is probably not a great idea, but at least now you know it's possible.