CSV

Contents
Read rows
Headers on
Write CSV
Converters

Read rows

The csv library parses comma separated files without manual splitting. Require csv once and read the whole file into nested arrays.

Each inner array is one row, so rows zero holds the header line when the file starts with column names.

require "csv" rows = CSV.read("data.csv") puts rows.inspect

Headers on

Positional indexes break as soon as columns move. Turn headers on and address every value by column name instead.

Foreach streams one row at a time, which keeps memory flat even for large exports.

require "csv" CSV.foreach("data.csv", headers: true) do |row| puts row["name"] end

Write CSV

Writing mirrors reading. Open a file for writing and push one array per row into the writer object.

The library adds quotes and escapes only where needed, so commas inside values stay safe.

require "csv" CSV.open("out.csv", "w") do |csv| csv << ["name", "age"] csv << ["Ada", 36] end

Converters

Every CSV value arrives as text by default. Pass the numeric converter to turn digit columns into Integer and Float values.

Header names stay strings while number cells arrive converted, which removes a whole layer of manual conversion calls.

require "csv" CSV.foreach("data.csv", headers: true, converters: :numeric) do |row| puts row["age"].class end

Next: ERB templates

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: