将哈希数组转换为csv文件 [英] convert array of hashes to csv file
本文介绍了将哈希数组转换为csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将哈希数组转换为.csv文件?
How do you convert an array of hashes to a .csv file?
我尝试过
CSV.open("data.csv", "wb") do |csv|
@data.to_csv
end
但它为空
推荐答案
尝试一下:
CSV.open("data.csv", "wb") do |csv|
@data.each do |hash|
csv << hash.values
end
end
如果您希望CSV的第一行包含哈希键(有点像标题),只需执行以下操作:
If you want the first line of the CSV to contain the keys of the hash (kind of like a header), simply do:
CSV.open("data.csv", "wb") do |csv|
csv << @data.first.keys # adds the attributes name on the first line
@data.each do |hash|
csv << hash.values
end
end
请在下面阅读@cgenco的评论:他为Array类写了一个猴子补丁.
Please read the comment of @cgenco below: He wrote a monkey patch for the Array class.
这篇关于将哈希数组转换为csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文