11

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.

Sergio
  • 28,539
  • 11
  • 85
  • 132
sf2k
  • 592
  • 2
  • 6
  • 25

3 Answers3

29

Use

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

which generates that CSV

first,second,third
column one,,column three
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
  • I had a situation where I used the split method on a string with delimiters where there were blank 'fields', for example a tab delimited string would be `"name\tage\t\t\tbirthday\n"` and the resulting array for those blank fields became double quotes (""). Here's what I did to generate nils in the array: `csv << string.split(/\t/).map { |f| f == "" ? nil : f }` – Mosab Sasi Jan 10 '17 at 01:48
1

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

Sveredyuk
  • 137
  • 9
1

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.

goetz
  • 2,018
  • 2
  • 30
  • 33