ruby 18 lines · 6 steps

Parsing one CSV transaction row in Ruby

A single row string is validated, split, and coerced into a clean, typed transaction hash.

Explained by highlit
1require "csv"
2 
3def parse_transaction_row(line)
4 fields = CSV.parse_line(line, headers: false, skip_blanks: true)
5 return nil if fields.nil? || fields.empty?
6 
7 id, amount, description, tags = fields
8 
9 {
10 id: Integer(id),
11 amount: BigDecimal(amount),
12 description: description.to_s.strip,
13 tags: tags.to_s.split("|").map(&:strip).reject(&:empty?)
14 }
15rescue CSV::MalformedCSVError => e
16 Rails.logger.warn("Skipping malformed row: #{e.message}")
17 nil
18end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Coercing raw strings into real types (Integer, BigDecimal) at the boundary keeps downstream code honest.
  2. 2BigDecimal, not Float, is the right choice for money to avoid rounding errors.
  3. 3A method-level rescue turns a parse failure into a skipped row instead of a crash.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing one CSV transaction row in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code