Library contents

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

  1. Start with CSV row containing A,2
  2. Do this Parse the two fields
  3. Result A and 2
The comma marks the field boundary. A header can supply names for those fields.

Syntax

Ruby 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.

From the programtext = "item,qty\n\"bolts, steel\",3\nnuts,1\n"
First output linebolts, steel 6
lesson.rb
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
Output
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

Advertisements

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?

Given"clay, red",7
Worked resultclay, red

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?

Given"lead, stereo",2
Worked resultlead, stereo