Codectionary / Developer documentation / Ruby

CSV with Named Columns

CSV handles quoted fields and row boundaries correctly. With headers enabled, each row supports lookup by column name. Require the csv gem; availability as a bundled gem varies by Ruby distribution. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

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"]) }
  1. Expected output: Tea, green 5
  2. 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

Specifications & further reading