CSV with fastercsv

I am creating a csv file with fastercsv.

require 'fastercsv'
FasterCSV.open("file.csv", "w") do |csv|
  csv << [45678, 45678, "stringa"]
end

I would also print the last cell in quotation marks. Is there anyone who
can help me?

Fil Sesto wrote:

I would also print the last cell in quotation marks.

I also want to print the quotes in the last cell.

This isn't a Rails question.

But, can't you just put the double quotes insides single quotes?

csv << [45678, 45678, '"stringa"']

Tim Shaffer wrote:

This isn't a Rails question.

But, can't you just put the double quotes insides single quotes?

csv << [45678, 45678, '"stringa"']

Seconded, this is a Ruby question.

Single quotes will work perfectly. You could also use %Q

csv << [45678, 45678, %Q{stringa}]

If you look at the spec for CSV, the proper contents of file.csv are:

45678,45678,stringa

You might put quotes around the string, but they are not needed for the file to be valid. However, if you had a comma in the string
   csv << [1,2,"a,b"]
then the file will contain
1,2,"a,b"
so that the comma isn't seen as a value separator.

Be aware that FasterCSV (which is just CSV in Ruby1.9) is quite strict about adherence to the standard and many files that CSV will complain are malformed will be quietly parsed by MS-Excel. (Yes, I know you must be shocked about that :wink:

-Rob

Rob Biedenharn
Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/
rab@GaslightSoftware.com http://GaslightSoftware.com/

if I write:
csv << [45678, 45678, '"stringa"']

the result is:

45678,45678,"""stringa"""

:frowning:

But I would like this:

45678,45678,"stringa"

You might "like" it, but the "quotes" are not needed in CSV unless the value requires them to be present (such as the presence of a comma or a quote.

Look at what you get with:

puts CSV.generate {|csv|
   csv << [1,'a','"b"', 'c,c', 'd"d']
}

-Rob

Rob Biedenharn
Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/
rab@GaslightSoftware.com http://GaslightSoftware.com/

Thanks! :slight_smile:

I am creating a csv file with fastercsv.

require 'fastercsv'
FasterCSV.open("file.csv", "w") do |csv|
csv << [45678, 45678, "stringa"]
end

I would also print the last cell in quotation marks. Is there anyone who
can help me?

You may want :force_quotes...

:force_quotes: When set to a true value, FasterCSV will quote all CSV fields it creates.

FasterCSV.open("file.csv", "w", :force_quotes => true).....

That may also quote the numbers, I don't recall...

-philip