Skip to content

Instantly share code, notes, and snippets.

@Snarp
Created April 10, 2023 19:07
Show Gist options
  • Save Snarp/d04178491218f9881bfd280ded011ae9 to your computer and use it in GitHub Desktop.
Save Snarp/d04178491218f9881bfd280ded011ae9 to your computer and use it in GitHub Desktop.
Array of hashes to CSV
require 'csv'
def hash_array_to_csv(hash_arr, fname='csv.csv')
headers = hash_arr.map{|hsh| hsh.keys}.flatten.uniq
csv = CSV.generate do |csv|
csv << headers
hash_arr.each do |hsh|
csv << (headers.map{|k| hsh[k]})
end
end
File.write(fname, csv) if fname
return csv
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment