我正在使用 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 编写器对你来说已经足够好了:
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
关于ruby - 如何正确写入CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10702895/