Syntax
CSV.parse(text, headers: true)Examples
CSV with Named Columns
Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
require "csv"
text = "name,quantity\n\"Tea, green\",3\nCoffee,2\n"
rows = CSV.parse(text, headers: true)
puts rows[0]["name"]
puts rows.sum { |row| Integer(row["quantity"]) }- Expected output: Tea, green 5
- The comma inside the quoted name remains part of one field. Quantities are converted explicitly from strings before addition.
Best practices
- Use CSV instead of splitting lines on commas.
- Declare gem "csv" in a Bundler project and validate expected headers.
Runtime & versions
Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Ruby documentation