CSV

suggest change

Comma-Separated Values (CSV) is one of the most widely used plain-text formats for tabular data interchange. Ruby includes a powerful, feature-rich csv module in its standard library that supports streaming line-by-line reads, header mapping, automated type conversions, custom delimiters, and in-memory generation.


1. Requiring the Library

Ruby's CSV functionality ships with Ruby (since Ruby 3.4 as a bundled gem, so under Bundler add gem 'csv' to your Gemfile):

require 'csv'

2. Reading CSV Data

Ruby provides multiple ways to read CSV data depending on file size and memory requirements.

Reading the Entire File into Memory (CSV.read)

CSV.read loads the whole file into memory and returns an array of arrays:

require 'csv'

rows = CSV.read('users.csv')
rows.each do |row|
  puts "Name: #{row[0]}, Email: #{row[1]}, Role: #{row[2]}"
end

Memory-Efficient Streaming with CSV.foreach

For large files, loading the entire file into RAM can cause high memory consumption. CSV.foreach streams the file line by line:

require 'csv'

CSV.foreach('large_transactions.csv') do |row|
  # Processes one line at a time
  puts "Transaction ID: #{row[0]}, Amount: #{row[1]}"
end

Parsing CSV from a String (CSV.parse)

To parse CSV content directly from a variable or network payload:

csv_string = <<~CSV
  Alice,30,Engineer
  Bob,25,Designer
CSV

data = CSV.parse(csv_string)
#=> [["Alice", "30", "Engineer"], ["Bob", "25", "Designer"]]

3. Working with Headers and Converters

By default, CSV rows are plain arrays accessed by numerical index. Enabling headers: true converts rows into CSV::Row objects that can be accessed by column name.

Header Mapping

csv_text = <<~CSV
  id,full_name,email,created_at
  101,Jane Doe,jane@example.com,2026-01-15
  102,John Smith,john@example.com,2026-02-20
CSV

CSV.parse(csv_text, headers: true) do |row|
  puts "#{row['full_name']} <#{row['email']}>"
  # Convert a CSV row directly to a Ruby Hash:
  puts row.to_h.inspect
end

Symbolized Headers and Type Converters

You can symbolize headers and automatically parse numeric strings and dates using built-in converters:

csv_text = <<~CSV
  name,score,active
  Alice,98.5,true
  Bob,84.0,false
CSV

table = CSV.parse(
  csv_text,
  headers: true,
  header_converters: :symbol, # Converts headers to lowercase symbols (:name, :score)
  converters: :numeric         # Automatically parses integers and floats
)

table.each do |row|
  puts "#{row[:name]}: #{row[:score].class} (value: #{row[:score]})"
  #=> Alice: Float (value: 98.5)
end

4. Writing CSV Files and Strings

Writing to a File (CSV.open)

Use CSV.open in write mode ("w"). Rows are appended using the shovel operator (<<):

require 'csv'

headers = ['Product ID', 'Name', 'Price', 'Stock']

CSV.open('inventory.csv', 'w', write_headers: true, headers: headers) do |csv|
  csv << [1, 'Mechanical Keyboard', 89.99, 15]
  csv << [2, 'Ergonomic Mouse', 59.50, 42]
  csv << [3, 'USB-C Cable', 12.00, 150]
end

Generating a CSV String in Memory (CSV.generate)

When creating downloadable CSV exports in web applications (Sinatra, Hanami, Rails):

require 'csv'

users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob',   role: 'member' }
]

csv_string = CSV.generate(headers: true) do |csv|
  csv << ['ID', 'Name', 'Role'] # Header row

  users.each do |u|
    csv << [u[:id], u[:name], u[:role]]
  end
end

puts csv_string

5. Custom Separators and Quoting Options

CSV files from different software (such as Excel regional exports) often use tabs or semicolons instead of commas. You can customize separators and quoting rules:

# Tab-Separated Values (TSV)
tsv_data = CSV.read('export.tsv', col_sep: "\t")

# European Semicolon-Separated Format
CSV.open('euro_report.csv', 'w', col_sep: ';', force_quotes: true) do |csv|
  csv << ['Produit', 'Prix en Euros']
  csv << ['Café', '2,50']
end

Handling Byte Order Marks (BOM) in UTF-8

Microsoft Excel often prepends a Byte Order Mark (\xEF\xBB\xBF) to UTF-8 CSV exports. If unhandled, this corrupts the name of the first column header. To strip it automatically, specify the 'bom|utf-8' encoding:

CSV.foreach('excel_export.csv', headers: true, encoding: 'bom|utf-8') do |row|
  puts row.headers # First header will not contain hidden BOM bytes
end

6. Handling Malformed CSVs

Corrupted data or unmatched quotes raise a CSV::MalformedCSVError. Wrap external inputs in exception handling:

begin
  CSV.parse("unclosed,\"quote\nstring", headers: false)
rescue CSV::MalformedCSVError => e
  puts "Failed to parse CSV: #{e.message}"
end

Best Practices

  1. Always Use CSV.foreach for Large Files: Avoid CSV.read on files larger than a few megabytes to prevent runaway memory usage.
  2. Specify Encodings Explicitly: When consuming CSVs from third-party sources or legacy systems, specify encoding: 'utf-8' or encoding: 'bom|utf-8' to avoid ArgumentError: invalid byte sequence.
  3. Prefer headers: true: Referencing fields by column name makes code far more resilient to column reordering than hardcoded array indices (row[3]).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents