简体   繁体   English

CSV.generate在字符串中添加引号

[英]CSV.generate adds quotation marks to strings

I am generating CSV files this way: 我通过这种方式生成CSV文件:

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. 我正在尝试摆脱这种行为,但是到目前为止我却迷路了...字符串Cat是从数据库加载的,没有引号。 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. 但是结果是一样的-引号仍然在最终生成的CSV文件中。

Any tip how to get rid of it? 任何提示如何摆脱它?

I'm not seeing the problem using some simple Ruby code to poke at CSV: 我看不到使用一些简单的Ruby代码戳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: 如果我细分生成的CSV似乎表现良好:

['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: 使用generate和block重新generate代码:

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"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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