tags:

views:

333

answers:

2

I am generating a CSV file from Ruby. The problem is a column string will contain double quotes, single quotes. How can I escape these things?

"Mary had a little so called \"lamb\"","34","none"
"something is not \"right\"","23","none"

Each column is enclosed in double quotes followed by comma (and no space), and written into a file.

Additionally, how do you insert CSV into MySQL? Would you need to use something like PHP's mysql_real_escape_string?

+2  A: 

Use FasterCSV. Do not roll your own CSV generation.

http://fastercsv.rubyforge.org/

Mike H
Unless he is looking for something very specific that FasterCSV doesn't have.
Chirantan
Agreed, however I find that unlikely. The advice "use the library, do not roll your own" is a cliche, but it is a cliche for a reason. The vast majority of the time, it's the correct advice.
Mike H
+1  A: 

Writing CSV data is easy, the simplest way is to replace every instance of a double quote with 2 double quotes and then surround the whole thing in double quotes. Alternatively, if your data does not contain double quotes, commas, carriage returns, linefeeds, or leading/trailing space, you don't have to surround the data with quotes or worry about escaping. You can find more information here.

Parsing CSV is much more complex, especially if you try to handle various forms of malformed data out there, in this case you almost certainly want to use an existing module.

Robert Gamble