Ruby等价于Python的DictWriter?
问题描述:
我有一个Ruby脚本,通过CSV,确定一些信息,然后放出一个生成的CSV文件。在Python中,我可以分别使用DictReader和DictWriter打开我的源文件和结果文件,并将行写入字典,其中键是文件头的值。在Ruby中似乎没有可行的方法来做到这一点,但我希望有人能指点我一个更好的解决方案,而不是将所有结果散列存储在数组中,并在事后写入它们。Ruby等价于Python的DictWriter?
答
当启用标题时,标准库“CSV”为行提供类似散列的行为。
require 'csv'
CSV.open("file.csv", "wb") do |csv_out|
CSV.foreach("test.csv", headers: true) do |row|
row["header2"].upcase! # hashlike behaviour
row["new_header"] = 12 # add a new column
csv_out << row
end
end
(test.csv具有头1,一个HEADER2和一些随机逗号分隔串线。)
FasterCSV宝石的Ruby? FasterCSV的[Documentation](http://fastercsv.rubyforge.org/classes/FasterCSV.html)。 – vgoff