Monday, October 8, 2007

Ruby: Redirecting standard Input, Output or Error

Sometimes we may postulate to save the output of the program or errors generated in the program into a file or a file type object instead of sending them to default IO objects.

This technique is very simple in shell programming from the command prompt, but not too hard to achieve from the ruby.

The solution is pretty simple, Assign the IO object like a File, Socket to the the global variables such as $stdin, $stdout and/or $stderr.

Take a stab into this small chunk of ruby code, that will explicate everything mostly.

#/auto/itasca/tools/bin/ruby -w
require 'stringio'
new_stdout = StringIO.new #new_stdout is an stringIO object
$stdout = new_stdout #assign this object variable to the gloabal variable
puts "Hello Maruthi."
puts "I am writing to standard output"

$stderr.puts "The screen output will not shown"
$stderr.puts new_stdout.string

* Write the output to the StringIO object.
* Just set
$stdout at the start of your program.
* Since
$std objects are global variables, even temporary changes affects all threads in your scripts.
* The standard input, output and error streams of the process are always available as a constants STDIN, STDOUT and STDERR respectively.