How to Read CSV Files in Ruby: Simple Guide with Examples
In Ruby, you can read CSV files using the built-in
CSV library by requiring it with require 'csv' and then using CSV.foreach or CSV.read to process the file line by line or all at once. This allows you to easily access each row as an array or hash for further processing.Syntax
The basic syntax to read a CSV file in Ruby involves requiring the csv library and then using methods like CSV.foreach or CSV.read.
require 'csv': Loads the CSV library.CSV.foreach('file.csv') do |row| ... end: Reads the file line by line, yielding each row as an array.CSV.read('file.csv'): Reads the entire file and returns an array of arrays.- You can pass options like
headers: trueto treat the first row as headers and get rows as hashes.
ruby
require 'csv' CSV.foreach('path/to/file.csv', headers: true) do |row| puts row['ColumnName'] end
Example
This example reads a CSV file with headers and prints each row's data by column name.
ruby
require 'csv' # Sample CSV content saved in 'data.csv': # Name,Age,City # Alice,30,New York # Bob,25,Los Angeles CSV.foreach('data.csv', headers: true) do |row| puts "Name: #{row['Name']}, Age: #{row['Age']}, City: #{row['City']}" end
Output
Name: Alice, Age: 30, City: New York
Name: Bob, Age: 25, City: Los Angeles
Common Pitfalls
Common mistakes when reading CSV files in Ruby include:
- Not requiring the
csvlibrary before using it. - Forgetting to set
headers: truewhen the CSV has headers, which causes you to access columns by index instead of name. - Using
CSV.readwithout handling large files, which can consume a lot of memory. - Not handling encoding issues if the CSV file uses a different character set.
ruby
require 'csv' # Wrong: Missing headers option CSV.foreach('data.csv') do |row| puts row['Name'] # This will be nil because headers are not set end # Right: Use headers: true CSV.foreach('data.csv', headers: true) do |row| puts row['Name'] end
Quick Reference
| Method | Description | Example |
|---|---|---|
| require 'csv' | Loads the CSV library | require 'csv' |
| CSV.foreach(file, headers: true) { |row| ... } | Reads file line by line with headers | CSV.foreach('file.csv', headers: true) { |row| puts row['Name'] } |
| CSV.read(file) | Reads entire file into array of arrays | rows = CSV.read('file.csv') |
| CSV.parse(string) | Parses CSV data from a string | CSV.parse(csv_string) { |row| ... } |
Key Takeaways
Always require the CSV library with
require 'csv' before reading files.Use
CSV.foreach with headers: true to read CSV files with headers easily.Avoid loading very large CSV files entirely into memory with
CSV.read.Access columns by name when headers are enabled for clearer code.
Handle encoding and file path issues to prevent runtime errors.