Raja S. (raja / cs.indiana.edu) wrote:
> I can't seem to find Ruby's version of dup2 and friends.
> How does one redirect output in Ruby?
> 
> I'm trying to write something along the lines of
> 
>   File.with_output_to_file ("foobar", "w") {
>     puts "Hello"
>     puts "World"
>     system("ls")
>   }

Try the following (untested):

def File.with_output_to_file(*args)
  # Args can be String plus w/a mode as in File.open or an IO object.
  # Responsibility for closing an IO object lies with the caller.
  begin
    save_stdout = $stdout.clone # a dup by any other name
    $stdout.reopen(*args)       # dup2, essentially
    yield                       # call the block
  ensure
    $stdout.reopen(save_stdout) # restore original $stdout
    save_stdout.close           # and dispose of the copy
  end
end

			Reimer Behrends