在 Ruby 中将数组输出到 CSV [英] Output array to CSV in Ruby

查看:38
本文介绍了在 Ruby 中将数组输出到 CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Ruby 将 CSV 文件读入数组很容易,但我找不到关于如何将数组写入 CSV 文件的任何好的文档.谁能告诉我怎么做?

It's easy enough to read a CSV file into an array with Ruby but I can't find any good documentation on how to write an array into a CSV file. Can anyone tell me how to do this?

如果重要的话,我使用的是 Ruby 1.9.2.

I'm using Ruby 1.9.2 if that matters.

推荐答案

到文件:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

到一个字符串:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

这是关于 CSV 的当前文档:http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

这篇关于在 Ruby 中将数组输出到 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆