Aniruddha Aniruddha - 1 month ago 10
Ruby Question

Writing to csv is adding quotes

I have string values which I am writing to csv file in the form of array as -

output = "This is a, ruby output"
CSV.open("output/abc.csv", "a+") do |csv|
csv << [output]
end


When I check my file
abc.csv
the row added has quotation marks (") at the start and end of the field. How can I get rid of it?

File output as ---

"This is a, ruby output"


So far I've tried
tr
or
slice
before saving to csv, but it seems writing is causing it.

Answer

If you get rid of the quotes then your output is no longer CSV. The CSV class can be instructed to use a different delimiter and will only quote if that delimiter is included in the input. For example:

require 'csv'
output = "This is a, ruby output"
File.open("output/abc.csv", "a+") do |io|
  csv = CSV.new(io, col_sep: '^')
  csv << [output, "the end"]
end

Output:

This is a, ruby output^the end
Comments