如何正确写入CSV文件

我正在使用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] 

提前致谢..

 csv << "\n" 

Stackoverflow在答案中需要30个字符,但我不知道还能说些什么。

我认为一般的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