开发者

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? 开发者_StackOverflowData could be empty variables but it should still write the commas.


Use

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

which generates that CSV

first,second,third
column one,,column three


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜