0
0
RubyHow-ToBeginner · 3 min read

How to Write CSV Files in Ruby: Simple Guide with Examples

In Ruby, you can write CSV files using the built-in CSV library by calling CSV.open with a filename and mode, then writing rows with csv << row_array. This method handles formatting and escaping automatically.
📐

Syntax

To write a CSV file in Ruby, use CSV.open with the filename and mode 'w' for writing. Inside the block, use csv << row to add each row as an array of values.

  • CSV.open(filename, 'w'): Opens the file for writing.
  • csv << row_array: Adds a row to the CSV file.
  • The block ensures the file is closed automatically.
ruby
require 'csv'

CSV.open('file.csv', 'w') do |csv|
  csv << ['header1', 'header2', 'header3']
  csv << ['value1', 'value2', 'value3']
end
💻

Example

This example writes a CSV file named people.csv with headers and two rows of data. It shows how to open the file, write headers, and add multiple rows.

ruby
require 'csv'

CSV.open('people.csv', 'w') do |csv|
  csv << ['Name', 'Age', 'City']
  csv << ['Alice', 30, 'New York']
  csv << ['Bob', 25, 'Los Angeles']
end

puts "CSV file 'people.csv' created with 3 rows."
Output
CSV file 'people.csv' created with 3 rows.
⚠️

Common Pitfalls

Common mistakes when writing CSV files in Ruby include:

  • Forgetting to require the csv library.
  • Not opening the file in write mode 'w', which can cause errors or append data unexpectedly.
  • Writing rows as strings instead of arrays, which will not format correctly.
  • Not closing the file, which CSV.open with a block handles automatically.

Here is an example of a wrong and right way:

ruby
require 'csv'

# Wrong: writing strings instead of arrays
CSV.open('wrong.csv', 'w') do |csv|
  csv << ["Name", "Age", "City"]  # This writes one row with columns
end

# Right: writing arrays for each row
CSV.open('right.csv', 'w') do |csv|
  csv << ['Name', 'Age', 'City']
end
📊

Quick Reference

MethodDescription
CSV.open(filename, 'w') { |csv| ... }Open a CSV file for writing with automatic closing
csv << row_arrayAdd a row to the CSV file as an array of values
require 'csv'Load the CSV library before using it
'w' modeWrite mode to create or overwrite the file
Use arrays for rowsEach row must be an array, not a string

Key Takeaways

Always require the built-in CSV library before writing CSV files.
Use CSV.open with 'w' mode and a block to write and auto-close the file.
Write each row as an array of values to format CSV correctly.
Avoid writing rows as plain strings; this breaks CSV structure.
The CSV library handles escaping and formatting automatically.