14
@out = File.open("#{File.expand_path("CSV")}/#{file_name}.csv", "w")
CSV::Writer.generate(@out) do |csv|
  csv << ["01", "02", "test"]
end
@out.close

When i run above code it stores the values in CSV as

01, 02. test

I want them to store as

"01", "02", "test"

Phrogz
  • 296,393
  • 112
  • 651
  • 745
vasu
  • 391
  • 3
  • 13
  • 1
    You may want to check out FasterCSV http://fastercsv.rubyforge.org/ . It has the option for specifying the quote character. I believe it will be the default CSV reader/writer in Ruby 1.9. – Rob Di Marco Apr 29 '11 at 12:03
  • 2
    @Rob FasterCSV _is_ the `CSV` library that ships in the standard library with 1.9 (and has for a long time now). – Phrogz Apr 29 '11 at 15:51

2 Answers2

24

Change

CSV::Writer.generate(@out)do |csv|

to

CSV::Writer.generate(@out, {:force_quotes=>true}) do |csv|
steenslag
  • 79,051
  • 16
  • 138
  • 171
-3

So why not double quote them?

@out = File.open("#{File.expand_path("CSV")}/#{file_name}.csv", "w")
CSV::Writer.generate(@out) do |csv|
  csv << ['"01"', '"02"', '"test"']
end
@out.close
Gressie
  • 507
  • 2
  • 7
  • 4
    """01""","""02""","""test""" this is the output when you open the csv if you double quote them – vasu Apr 29 '11 at 12:59