sf2k
sf2k

Reputation: 602

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

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.

Upvotes: 12

Views: 9094

Answers (3)

goetz
goetz

Reputation: 2263

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.

Upvotes: 1

Sveredyuk
Sveredyuk

Reputation: 137

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

Upvotes: 1

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Use

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

which generates that CSV

first,second,third
column one,,column three

Upvotes: 30

Related Questions