Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert array of hashes to csv file

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


2 Answers

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 (a header row), 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.

like image 127
MrYoshiji Avatar answered Sep 03 '25 13:09

MrYoshiji


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
like image 33
nbrustein Avatar answered Sep 03 '25 14:09

nbrustein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!