From: Eric Hodel Date: 2006-05-18T03:35:08+09:00 Subject: Re: Capturing stdout On May 17, 2006, at 5:26 AM, Mark Volkmann wrote: > On 5/17/06, Daniel Harple wrote: >> 2006/5/17, Damphyr : >>> 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. >> >> require 'stringio' >> stdout = StringIO.new >> $stdout = stdout >> load "file1.rb" >> $stdout = STDOUT >> stdout.rewind >> puts "got: #{stdout.read}" # => got: Output of meaningful code >> omitted > > Here's another alternative. > > # Create a string object to receive the output. > dest = '' > > # Add a write method to this string object. > def dest.write(data); self << data; end How is this better than using StringIO? -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com