Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Read and Write CSV with Quotes

Tags:

ruby

csv

I'd like to read in a csv row, update one field then output the row again with quotes.

Row Example Input => "Joe", "Blow", "[email protected]"
Desired Row Example Output => "Joe", "Blow", "[email protected]"

My script below outputs => Joe, Blow, [email protected]

It loses the double quotes which I want to retain.

I've tried various options but no joy so far .. any tips?

Many thanks!

require 'csv'

CSV.foreach('transactions.csv',
            :quote_char=>'"',
            :col_sep =>",", 
            :headers => true, 
            :header_converters => :symbol ) do |row| 

row[:customer_email] = '[email protected]'

puts row

end
like image 710
Rudi Starcevic Avatar asked Jun 13 '13 05:06

Rudi Starcevic


2 Answers

Quotes in CSV fields are usually unnecessary, unless the field itself contains a delimiter or a newline character. But you can force the CSV file to always use quotes. For that, you need to set force_quotes => true:

CSV.foreach('transactions.csv',
            :quote_char=>'"',
            :col_sep =>",", 
            :headers => true, 
            :force_quotes => true,
            :header_converters => :symbol ) do |row| 
like image 132
Tim Pietzcker Avatar answered Oct 05 '22 02:10

Tim Pietzcker


You can manually add them to all your items

Hash[row.map { |k,v| [k,"\"#{v}\""] }]

(edited because I forgot you had a hash and not an array)

like image 22
Justin L. Avatar answered Oct 05 '22 02:10

Justin L.