Ruby system example - how to make system calls and redirect output to a file

I still have a lot to learn about Ruby, but here's a Ruby script that runs a series of system commands (Kernel.system()), which in my case means calling a series of JRuby scripts. I send all of the output from this script and from the system calls to a file by (a) writing directly to the file using Ruby and (b) redirecting STDOUT when making each system() call. I think this is a hack, but I can't find a better way to redirect STDOUT.

#
# a ruby script to run a series of system calls,
# and put their output into one file.
#
# Alvin Alexander, DevDaily.com
#

# the output file for your scripts:
@filename = "scripts.out"

# the list of scripts you want to run:
scripts_to_run = [ 'foo1.rb', 
                   'foo2.rb'
]


# --------------------------------
# don't change anything below here
# --------------------------------

def write_to_file (s)
  f = File.open(@filename,'a')
  f.puts s
  f.close
end

def get_formatted_time
  t = Time.now
  t_out = t.strftime("%H:%M:%S%p (%m/%d/%Y)")
end

scripts_to_run.each { |s|
  write_to_file "\nCalling #{s} at #{get_formatted_time} ..."
  system("jruby.bat #{s} >> #{@filename}")
  write_to_file "Script ended at #{get_formatted_time}."
}

You can adjust this to your own needs by changing the system() call near the end of the file. As mentioned I'm calling a series of JRuby scripts, but you'll probably want to call something else.

As I mentioned this is a hack, because I can't figure out how to properly redirect STDOUT when making a system call, so I took this approach to get the job done today. This lets me write to the same output file using the write_to_file method, while also redirecting STDOUT from the program I'm calling using the standard ">>" syntax.

I also add some time formatting and printing to the output file, so the actual output looks like this when I run it on my Windows system:

C:\Al\RobotStuff\Tests>type scripts.out

Calling foo1.rb at 12:02:58PM (01/27/2007) ...
foo1
Script ended at 12:02:59PM (01/27/2007).

Calling foo2.rb at 12:02:59PM (01/27/2007) ...
foo2
Script ended at 12:03:01PM (01/27/2007).