convert array of hashes to csv file

让人想犯罪 __ 提交于 2019-12-03 09:30:17

问题


How do you convert an array of hashes to a .csv file?

I have tried

    CSV.open("data.csv", "wb") do |csv|
      @data.to_csv
    end

but it is blank


回答1:


Try this:

CSV.open("data.csv", "wb") do |csv|
  @data.each do |hash|
    csv << hash.values
  end
end

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

Please read the comment of @cgenco below: He wrote a monkey patch for the Array class.




回答2:


If the hashes aren't uniform then you will end up with data in the wrong columns. You should use values_at instead:

CSV.open("data.csv", "wb") do |csv|
  keys = @data.first.keys
  csv << keys
  @data.each do |hash|
    csv << hash.values_at(*keys)
  end
end



回答3:


CSV is smart enough to deal with the non-uniform hashes for you. See the code for CSV::Writer#<<

So, this works, and is a bit simpler than the above examples:

CSV.open("data.csv", "wb", {headers: @data.first.keys} ) do |csv|
  @data.each do |hash|
    csv << hash
  end
end


来源:https://stackoverflow.com/questions/17325792/convert-array-of-hashes-to-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!