How to Write CSV Files in Ruby

09/20/2021
Contents
In this article, you will learn how to write CSV files in Ruby.
Writing CSV Files
In Ruby, you can write CSV (Comma Separated Values) files using the CSV library. Here’s an example of how to create and write data to a CSV file:
require 'csv'
# Array of data to be written to CSV file
data = [
["Name", "Age", "Gender"],
["John", 25, "Male"],
["Jane", 30, "Female"],
["Bob", 40, "Male"]
]
# Open CSV file for writing
CSV.open("output.csv", "w") do |csv|
# Write data to CSV file
data.each do |row|
csv << row
end
end
In this example, we require the CSV library, create an array of data to be written to the CSV file, and then open the file for writing using CSV.open.
We then loop through each row of data and write it to the CSV file using csv << row. Each row is automatically separated by a comma.
Finally, we close the CSV file with end.
The resulting CSV file will be created in the same directory as the Ruby file and will contain the data we wrote to it.