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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Coercing raw strings into real types (Integer, BigDecimal) at the boundary keeps downstream code honest.
- 2BigDecimal, not Float, is the right choice for money to avoid rounding errors.
- 3A method-level rescue turns a parse failure into a skipped row instead of a crash.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-one-csv-transaction-row-in-ruby-explained-ruby-77c6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.