From: Jim Weirich Date: 2002-08-18T02:49:19+09:00 Subject: Re: How do I dup file descriptors in ruby? (diverting STDERR) Richard> Thank you for the suggestion, but perhaps I should have Richard> been more specific about what I really want to do. The Richard> following is closer to what I'm interested in. It's a Richard> very common lick to play in Korn, perl and C and if I Richard> have to go through a symphony to do the same thing in Richard> ruby then, to paraphrase the great American poet Chuck Richard> Berry, I'll lose the beauty of the melody. Cute analogy :-) [... lick elided ...] Hmmm ... I count 6 extra lines for your lick. Fortunately, in Ruby you can capture licks in a JamMan effects box and replay the lick whenever you like. Write the following file one time and store it somewhere in your standard Ruby path. -- File: redirect.rb ------------------------------------------------- def redirect_to(fn) olddefout = $defout oldstderr = $stderr open(fn, "a") do |file| $defout = file $stderr = file begin yield ensure $defout = olddefout $stderr = oldstderr end end end ---------------------------------------------------------------------- Now, to playback your lick, just do ... require 'redirect' redirect_to("logfile.txt") { puts "output now goes to the log file" } Just three lines of overhead instead of the six. And it handles exceptions and early exits properly. -- -- Jim Weirich jweirich@one.net http://w3.one.net/~jweirich --------------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)