From: Sam Roberts Date: 2006-05-18T03:32:36+09:00 Subject: Re: Capturing stdout Quoting damphyr@freemail.gr, on Wed, May 17, 2006 at 07:49:34PM +0900: > I have code that prints to stdout (using puts and/or print). > I'm loading the code from a file (pretty much the way rake handles > rakefiles) and would like to capture the output from the loaded code. > I don't want to redirect stdout into a file or anywhere else, I need the > output in a string. > > ---file1.rb > puts "Output of meaningful code omitted" > ---loader.rb > > begin > ###do some magic to get the stdout from this point on into a string > load file1.rb > ###do some more magic to put stdout back where it was. > end > > Has anyone a solution for this? > (Now that I think of it would StringIO do for stdout redirection?) Yes, % ruby -rstringio -e'$stdout = StringIO.new; puts "hello"; $stderr.puts $stdout.string' hello