ruby-on-railsrubyruby-on-rails-5

The issue to write string in double quotes in the CSV


I am going to write a string in double quotes in the CSV using csv gem.

CSV.open(source_filename, "wb") do |csv|
  csv << ["NAME", "AGE"]
  csv << ["Oleg", 15]
end

The result is

NAME,AGE
Oleg,15

What I want to write is that

NAME,AGE
"Oleg","15"

Is there any way to write like this?


Solution

  • If you don't want literal quotes in the values, but simply want to wrap all values with quotes you can do so by setting the force_quotes option:

    csv = CSV.generate(force_quotes: true) do |csv|
      csv << ["NAME", "AGE"]
      csv << ["Oleg", 15]
    end
    
    puts csv
    

    Prints:

    "NAME","AGE"
    "Oleg","15"
    

    I use generate in this answer to simplify copy/pasting the code. You can use the same options with open. This then becomes CSV.open(source_filename, "wb", force_quotes: true).

    However when the above is read by an CSV implementation the quotes will not be part of the value. This is further explained by the answer of tadman.