From: Bruce Woodward Date: 2007-04-06T16:00:01+09:00 Subject: Re: A convoluted question about stdout ------=_Part_1837_13807860.1175842798834 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 4/6/07, Sonny Chee wrote: > > Hey Guys, > > I know I can do a $stdout.reopen and redirect it to a file. Is there a > more direct way to get at the contents of stdout... say, redirect stdout > to variable? > > #!/usr/bin/env ruby old_std_out = $stdout $stdout = File.open("/tmp/file", "w+") puts "where does the output go?" bruce@carlpowerbook:~/tmp$ rm -f /tmp/file bruce@carlpowerbook:~/tmp$ ./r.rb bruce@carlpowerbook:~/tmp$ cat /tmp/file where does the output go? bruce@carlpowerbook:~/tmp$ or, with build in clean up... bruce@carlpowerbook:~/tmp$ rm -f /tmp/file bruce@carlpowerbook:~/tmp$ cat r.rb #!/usr/bin/env ruby def with_stdout(file_name) old_stdout = $stdout $stdout = File.open(file_name, "w+") yield $stdout = old_stdout end with_stdout "/tmp/file" do puts "where does the output go?" end puts "and where is stdout now?" bruce@carlpowerbook:~/tmp$ ./r.rb and where is stdout now? bruce@carlpowerbook:~/tmp$ cat /tmp/file where does the output go? ------=_Part_1837_13807860.1175842798834--