Skip to content

Instantly share code, notes, and snippets.

@dalton-cole
Created March 17, 2020 15:09
Show Gist options
  • Save dalton-cole/201d225d40ff62759feaee32f869e3d8 to your computer and use it in GitHub Desktop.
Save dalton-cole/201d225d40ff62759feaee32f869e3d8 to your computer and use it in GitHub Desktop.
Ruby non-uniform hash array to csv
class Array
def to_csv(filename="hash.csv")
require 'csv'
# Get all unique keys into an array:
keys = self.flat_map(&:keys).uniq
CSV.open(filename, "wb") do |csv|
csv << keys
self.each do |hash|
# fetch values at keys location, inserting null if not found.
csv << hash.values_at(*keys)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment