且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将哈希数组转换为csv文件

更新时间:2023-02-14 11:13:47

尝试一下:

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.