ruby 如何正确写入CSV文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10702895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:08:35  来源:igfitidea点击:

How write into CSV file properly

rubycsv

提问by Kashiftufail

i am using ruby 1.9.2 and also use its csv library.I want to write in csv properly just

我正在使用 ruby​​ 1.9.2 并使用它的 csv 库。我想正确地用 csv 编写

like this

像这样

name,country_code,destination,code
Afghanistan,93,Bamain,51
Afghanistan,93,Bamain,52
Afghanistan,93,Bamain,53
Afghanistan,93,Parwan,91

My code is this

我的代码是这样的

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

I have mention above how puts i line break there in CSV file and also omit this sigh which

我在上面提到了如何将我的换行符放在 CSV 文件中,并省略了这个叹息

covers every row in CSV"[]"

涵盖 CSV 中的每一行"[]"

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

Thanks in advance..

提前致谢..

回答by ABrukish

I think general CSV writer will be good enough for you:

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

回答by Marlin Pierce

csv << "\n"

Stackoverflow requires 30 characters in an answer, but I don't know what more to say.

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