0
0
Rubyprogramming~5 mins

CSV library basics in Ruby

Choose your learning style9 modes available
Introduction

CSV files store data in tables using commas. Ruby's CSV library helps read and write these files easily.

You want to read data from a spreadsheet saved as CSV.
You need to save program data in a simple table format.
You want to share data with other programs using CSV files.
You want to process CSV data line by line in your Ruby script.
Syntax
Ruby
require 'csv'

# Reading CSV
CSV.foreach('file.csv') do |row|
  # use row array
end

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

Use require 'csv' to load the CSV library.

CSV.foreach reads each row as an array.

Examples
This reads each row from data.csv and prints it as an array.
Ruby
require 'csv'

CSV.foreach('data.csv') do |row|
  puts row.inspect
end
This writes three rows to output.csv, including headers and data.
Ruby
require 'csv'

CSV.open('output.csv', 'w') do |csv|
  csv << ['Name', 'Age']
  csv << ['Alice', 30]
  csv << ['Bob', 25]
end
This reads all rows at once and prints the first row as a comma-separated string.
Ruby
require 'csv'

rows = CSV.read('data.csv')
puts rows[0].join(', ')
Sample Program

This program first creates a CSV file named people.csv with two columns and two data rows. Then it reads the file and prints each person's name and city.

Ruby
require 'csv'

# Write CSV file
CSV.open('people.csv', 'w') do |csv|
  csv << ['Name', 'City']
  csv << ['John', 'New York']
  csv << ['Jane', 'Los Angeles']
end

# Read and print CSV file
CSV.foreach('people.csv') do |row|
  puts "Name: #{row[0]}, City: #{row[1]}"
end
OutputSuccess
Important Notes

CSV rows are arrays where each element is a cell value.

Use CSV.foreach for large files to save memory.

Use CSV.read to load the whole file into memory as an array of arrays.

Summary

Ruby's CSV library makes reading and writing CSV files simple.

Use CSV.foreach to read line by line, and CSV.open to write.

Each CSV row is an array of strings representing the cells.