Skip to content

Instantly share code, notes, and snippets.

@januszm
Forked from christiangenco/hash_array_to_csv.rb
Created March 19, 2024 21:37
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 januszm/77037453a1c0c0b0bdeade303caca3f3 to your computer and use it in GitHub Desktop.
Save januszm/77037453a1c0c0b0bdeade303caca3f3 to your computer and use it in GitHub Desktop.
Ruby hash array to CSV
class Array
def to_csv(csv_filename="hash.csv")
require 'csv'
CSV.open(csv_filename, "wb") do |csv|
csv << first.keys # adds the attributes name on the first line
self.each do |hash|
csv << hash.values
end
end
end
end
# ex: [{a: 1, b: 2}, {a: 3, b: 4}].to_csv("hash.csv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment