如何正确地将内容写入CSV文件

20
我使用的是 Ruby 1.9.2 版本,同时也使用了它的 CSV 库。我想要正确地写入 CSV,就像这样。
name,country_code,destination,code
Afghanistan,93,Bamain,51
Afghanistan,93,Bamain,52
Afghanistan,93,Bamain,53
Afghanistan,93,Parwan,91

我的代码是这样的

def export_data
  @coun = Country.all(:limit => 10)
  header = "name,country_code,destination,code"
  file = "my_file.csv"
  File.open(file, "w") do |csv|
    csv << header
    @coun.each do |c|
      csv << [c.name, c.country_code, c.user_id, c.subscriber_id]       
      # How puts line break here
    end
  end
  send_file(file)
end

我已经提到过如何在CSV文件中换行,以及省略包含每一行CSV的"[]"标识符。

 Like   ["Finland",1,1,2334]

提前感谢。

2个回答

78

我认为一般的CSV写入程序就足够了:

require 'csv'
file = "my_file.csv"
CSV.open( file, 'w' ) do |writer|
  @coun.each do |c|
    writer << [c.name, c.country_code, c.user_id, c.subscriber_id]
  end
end

39
csv << "\n"

Stackoverflow要求回答至少包含30个字符,但我不知道还该说些什么。


1
使用 @abrukish 建议的 CSV 写入方式,可以避免包含逗号的值带来的一些麻烦。 - sekmo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接