Skip to content

Instantly share code, notes, and snippets.

@reggieb
Last active March 30, 2020 07:20
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 reggieb/f7af2aa3cd40bcd049a8eb62e281d8c3 to your computer and use it in GitHub Desktop.
Save reggieb/f7af2aa3cd40bcd049a8eb62e281d8c3 to your computer and use it in GitHub Desktop.
Create a CSV file from an array of hashes
require 'csv'
# This is the source data - basically an array of hashes
data = [
{a: 1, b: 2},
{a: 3, b: 4}
]
# This is a path to the file we are going to create.
# __dir__ is the directory of the current file - that is, this file's directory
# So this will create a path to a file 'csv_play.csv' in the same directory as this file
# The file doesn't need to exist - the next line will create it
path = File.join __dir__, 'csv_play.csv'
# This line opens the new file and the following lines write the data to it
CSV.open(path, 'wb') do |csv|
# The first line of the CSV needs to be the headers. That's the keys
# of the hashes. If we assume all the hashes have the same keys we can
# just pick the first one and use it's keys to create the first line
csv << data.first.keys
# Then we just iterate through the hashes, pushing the values of each
# into the csv.
data.each do |row|
csv << row.values
end
end
# If you run this file `ruby csv_play.rb`, a file will be created in the same directory
# The file will have the content:
#
# a,b
# 1,2
# 3,4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment