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 S. 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”’]

On Aug 20, 2010, at 6:50 AM, Filippo Salvatici wrote:

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?

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 B.
[email protected] http://AgileConsultingLLC.com/
[email protected] 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”

Tim S. 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}]

Thanks! :slight_smile:

On Aug 20, 2010, at 9:51 AM, Fil S. wrote:

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 B.
[email protected] http://AgileConsultingLLC.com/
[email protected] http://GaslightSoftware.com/

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs