Created
April 10, 2023 19:07
-
-
Save Snarp/d04178491218f9881bfd280ded011ae9 to your computer and use it in GitHub Desktop.
Array of hashes to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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