简体   繁体   中英

CSV.generate adds quotation marks to strings

I am generating CSV files this way:

csv_address_book = CSV.generate do |csv|
  @users.each do |u|  
    csv << ["Add", 
            nil,
            u.name,
            u.pet,
            nil,
            u.addreess,
            ..] 

It works well, but to some strings are attached quotation marks, so instead of:

A,Cat,123,B

I am getting

A,"Cat",123,B

I am trying to get rid of this behavior, but I am losing so far... The string Cat is loaded from database and there are no quotation marks. I've tried manually remove them, like

d.pet.gsub('"', '')

But the result is the same - the quotation marks are still in the final generated CSV file.

Any tip how to get rid of it?

I'm not seeing the problem using some simple Ruby code to poke at CSV:

require 'csv'

['A','Cat',123,'B'].to_csv # => "A,Cat,123,B\n"

If I break down the generation CSV seems to be behaving well:

['a', 'b'].to_csv # => "a,b\n"
['a b'].to_csv # => "a b\n"
['a,b'].to_csv # => "\"a,b\"\n"
['"a b"'].to_csv # => "\"\"\"a b\"\"\"\n"

Recreating your code using generate and a block:

csv_string = CSV.generate do |csv|
  csv << ['A','Cat',123,'B']
  csv << ['a', 'b']
  csv << ['a b']
  csv << ['a,b']
  csv << ['"a b"']
end

csv_string
# => "A,Cat,123,B\na,b\na b\n\"a,b\"\n\"\"\"a b\"\"\"\n"

puts csv_string
# >> A,Cat,123,B
# >> a,b
# >> a b
# >> "a,b"
# >> """a b"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM