File output

June 11, 2007

A fairly common thing I’ve run into is having an array of some kind, and wanting to dump that information into a file for visualization or processing. Dumping to a file is fairly easy to do in Ruby.

out = File.new('ouptut.txt','w')
my_array.each do |item|
    out.puts item
end
out.close

Which results in a file with each item of the array on its own line. I usually end up with nested arrays (x and y values, usually), which require a slight variation. The ‘w’ in the call to File.new is (as you might have guessed) for ‘write access’. Also do not forget to close the file when you are done.

out = File.new('ouptut.txt','w')
my_array.each do |item|
  out.puts "#{item[0]}     #{item[1]}"
end
out.close