Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby CSV, how to write a blank ,, instead of ,"", to a file?

Tags:

ruby

csv

ruby-1.9

Ruby 1.9 version of csv

header %w[first second third]

data = ["column one",,"column three"]

CSV.open("myfile.csv","w") do |csv|
  csv << header
  csv << data
end

In this simple example, the empty middle ,, in the data array causes an error but if empty quote are used ,"", then no error and the CSV file is created. However I want to make the CSV file not have an empty quoted segement.

Specifically how do I generate blank sections of a CSV file without quotes? Data could be empty variables but it should still write the commas.

like image 283
sf2k Avatar asked May 27 '11 19:05

sf2k


3 Answers

Use

data = ["column one",nil,"column three"]

which generates that CSV

first,second,third
column one,,column three
like image 93
Marcel Jackwerth Avatar answered Nov 19 '22 18:11

Marcel Jackwerth


And If you need new empty line just add double nils like: [nil, nil]

like image 1
Sveredyuk Avatar answered Nov 19 '22 18:11

Sveredyuk


Ruby 2.6 has quote_empty parameter for the constructor, which can be set to false.

:quote_empty

    When setting a true value, CSV will quote empty values with double quotes. When false, CSV will emit an empty string for an empty field value.

like image 1
goetzc Avatar answered Nov 19 '22 18:11

goetzc