From: James Edward Gray II Date: 2007-03-27T00:53:17+09:00 Subject: Re: capturing standard out? On Mar 19, 2007, at 5:18 PM, Giles Bowkett wrote: > Is there an easy way to capture standard out in Ruby, so that "puts" > throws its output into a buffer instead of just popping up on the > screen? I would do it like this: #!/usr/bin/env ruby -w require "stringio" def capture_stdout(buffer = StringIO.new) saved_stdout = $stdout $stdout = buffer yield $stdout = saved_stdout buffer.string rescue buffer end if __FILE__ == $PROGRAM_NAME puts "This will be printed." output = capture_stdout { puts "Meanwhile, this was captured." } puts "This also will be printed." p output end __END__ James Edward Gray II