File output

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
Advertisements

4 Responses to File output

  1. Anonymous coward says:

    I find this more Ruby like:

    File.new(‘output.txt’, ‘w’) do |f|
    f.print my_array.map do |n|
    “#{n[0]} #{n[1]}”
    end.join(“\n”)
    end

  2. Mystery Man says:

    One line:

    File.new(‘ouptut.txt’,’w’) {|f| f.write my_array.to_yaml}

    (OK, two lines if you need the ‘require yaml’)

  3. bcbroom says:

    Thanks for the comments. I haven’t quite wrapped my head around #map yet. My only problem with yaml is that I usually pipe data into a graphing program (xmgrace or gnuplot) and they both are looking for data like

    x y
    x y
    x y

    but I am definitely going to look at it some more for more general stuff.

  4. bcbroom says:

    It looks like to pass in a block, you need to use File.open instead of File.new. Thats a bit strange, I thought they were aliases for each other.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: