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:

File.open(local_filename, 'w') {|f| f.write(doc) }

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,

CSV.open(newfilename, "w+",
             :write_headers => true,
             :headers => arr_of_arrs.headers) do |csv|
    arr_of_arrs.each{|row| csv << row}
 end

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:

CSV.open(newfilename, "w+",
                :write_headers => true,
                :headers => arr_of_arrs.headers) do |csv|
   csv << arr_of_arrs
end