Created
March 17, 2020 15:09
-
-
Save dalton-cole/201d225d40ff62759feaee32f869e3d8 to your computer and use it in GitHub Desktop.
Ruby non-uniform hash array 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
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