Ruby CSV write to a file – Gotcha!

Unlike the beautifully concise and familiar 1 liner of code to dump a document to a text file:

[ruby toolbar=”true”]File.open(local_filename, ‘w’) {|f| f.write(doc) }[/ruby]

The ruby csv library requires quite a bit more typing, and the documentation for it is easy to misunderstand.

One of my primary needs, is often data wrangling.  Changing the contents of a csv file for use in another framework, whether it’s reverse coordinates, stripping unwanted columns, or adding needed columns to the data, and I always trip up on how to dump the changed CSV after manipulating it.

As a reminder to myself, and maybe a hint to others, I’ve include the proper way to dump out your arr_of_arrs, once you’ve manipulated it as you will,

[ruby highlight=”4″ toolbar=”true”]CSV.open(newfilename, "w+",
:write_headers => true,
:headers => arr_of_arrs.headers) do |csv|
arr_of_arrs.each{|row| csv << row}
end[/ruby]

The important bit is remembering to do an each loop of your arr_of_arrays object. This for instance will not produce the desired results:

[ruby highlight=”4″]CSV.open(newfilename, "w+",
:write_headers => true,
:headers => arr_of_arrs.headers) do |csv|
csv << arr_of_arrs
end[/ruby]

Leave a Reply

Your email address will not be published. Required fields are marked *