Skip to content

Instantly share code, notes, and snippets.

@joshjordan
Last active August 4, 2016 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshjordan/a6dcb5d3791f507dc2e10ed146737d2d to your computer and use it in GitHub Desktop.
Save joshjordan/a6dcb5d3791f507dc2e10ed146737d2d to your computer and use it in GitHub Desktop.
Snippet that saves an array of hashes to a CSV file easily
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