Last active
August 4, 2016 02:50
-
-
Save joshjordan/a6dcb5d3791f507dc2e10ed146737d2d to your computer and use it in GitHub Desktop.
Snippet that saves an array of hashes to a CSV file easily
This file contains hidden or 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' | |
class Array | |
def to_csv(csv_filename, homogeneous_headers = false) | |
return unless self.any? | |
headers = if homogeneous_headers | |
self.first.keys | |
else | |
self.inject([]) { |memo, row| memo |= row.keys; memo } | |
end | |
CSV.open(csv_filename, "wb") do |csv| | |
csv << headers | |
self.each do |hash| | |
row = headers.map { |h| hash[h] } | |
csv << row | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment