Ruby CSV.parse
CSV.parse with headers: true produces rows accessible by column name. Field values are strings unless a converter is supplied.
A simple example
CSV.parse
- Start with CSV row containing A,2
- Do this Parse the two fields
- Result A and 2
Syntax
rows = CSV.parse(text, headers: true)
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Read named columns and preserve a quoted comma
A supplier sends a CSV invoice whose quoted description contains a comma. Use a CSV reader that understands quoting so the amount stays in its proper column and the description remains intact.
require 'csv'
text = "item,qty\n\"bolts, steel\",3\nnuts,1\n"
CSV.parse(text, headers: true).each do |row|
puts "#{row['item']} #{Integer(row['qty'], 10) * 2}"
end
bolts, steel 6 nuts 2
The quoted comma belongs to the item name. Convert only the numeric column, so identifiers or labels containing leading zeros remain intact.
Ruby documentation for CSV.parse
Read an exhibit order
A curator enters a material and finish together inside a quoted item name. Read the quoted field as one CSV cell. What item name belongs to this row?
Read a studio purchase
A technician enters a cable description with a comma inside the field. Read the quoted field as one CSV cell. What item name belongs to this row?