CSV
| 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