Practical Use Cases
Parsing structured data.
Practical Use Cases is a free Ruby Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, and your progress syncs across the web and the CoddyKit app. The Ruby Academy course includes 4 lessons in total.
Why Pattern Matching Shines
Pattern matching is at its best when handling structured data: API responses, config trees, and parsed files. It replaces nested if/dig checks with one readable expression.
require 'json'
resp = JSON.parse('{"ok":true,"data":42}', symbolize_names: true)
case resp
in { ok: true, data: }
puts(data)
endHandling API Success and Error
Match different response shapes in distinct branches, extracting the right fields for each.
def handle(resp)
case resp
in { status: 'ok', result: }
"got #{result}"
in { status: 'error', message: }
"error: #{message}"
end
end
puts(handle({ status: 'error', message: 'bad input' }))Parsing Command Arguments
Match an array of arguments to dispatch commands cleanly.
def run(args)
case args
in ['add', a, b]
a.to_i + b.to_i
in ['echo', *rest]
rest.join(' ')
end
end
puts(run(['add', '3', '4']))
puts(run(['echo', 'hi', 'there']))Validating Record Shape
Use a pattern to assert that a record has the required fields and types before processing it.
def valid?(rec)
case rec
in { name: String, age: Integer => a } if a >= 0
true
else
false
end
end
puts(valid?({ name: 'Ada', age: 36 }))
puts(valid?({ name: 'X', age: -1 }))Destructuring Nested Config
Pull deep config values out in a single match instead of chained lookups.
cfg = { server: { host: 'localhost', port: 8081 } }
case cfg
in { server: { host:, port: } }
puts("#{host}:#{port}")
endTagged Unions
A common functional pattern: data tagged by type, dispatched by its tag.
def area(shape)
case shape
in { type: 'circle', r: }
(3.14 * r * r).round(2)
in { type: 'rect', w:, h: }
w * h
end
end
puts(area({ type: 'rect', w: 3, h: 4 }))Matching with deconstruct
Custom objects become matchable if they define deconstruct (for array patterns). Struct does this automatically.
Point = Struct.new(:x, :y)
case Point.new(1, 2)
in [x, y]
puts("#{x},#{y}")
endMatching with deconstruct_keys
Define deconstruct_keys for hash-pattern support. Struct provides this too, enabling named matching.
Point = Struct.new(:x, :y)
case Point.new(3, 4)
in { x:, y: }
puts("x=#{x} y=#{y}")
endClass with Pattern
Combine a type pattern with a hash pattern to match a specific class and its fields.
User = Struct.new(:name, :admin, keyword_init: true)
case User.new(name: 'Ada', admin: true)
in User(admin: true, name:)
puts("#{name} is an admin")
endSafe Fallbacks
Always provide an else when input may not match, turning an exception into graceful handling.
def parse(data)
case data
in { id: Integer => id }
"id #{id}"
else
'unrecognized'
end
end
puts(parse({ name: 'x' }))Putting It Together
A realistic flow: parse JSON, match its shape, validate with a guard, and act, all in one tidy expression.
require 'json'
event = JSON.parse('{"kind":"purchase","amount":150}', symbolize_names: true)
case event
in { kind: 'purchase', amount: Integer => amt } if amt > 100
puts("big purchase: #{amt}")
in { kind: 'purchase', amount: }
puts("purchase: #{amount}")
endQuick Check
Which method must a custom class define to support hash pattern matching like in { x:, y: }?
Recap: Practical Use Cases
You applied pattern matching to real problems:
- Dispatching API responses and commands
- Validating record shape with guards
- Destructuring nested config and tagged unions
deconstruct/deconstruct_keysfor custom objects- Always add
elsefor safe fallbacks
You have completed the Ruby Pattern Matching course.
case { type: 'circle', r: 2 }
in { type: 'circle', r: } then puts(3.14 * r * r)
endLearn Ruby with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 29
- Lessons
- 109
Frequently Asked Questions
Is the “Practical Use Cases” lesson free?
Yes — any 3 lessons of the Ruby Academy learning path, including “Practical Use Cases”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Ruby Academy course includes 4 lessons in total.
What will I learn in “Practical Use Cases”?
Parsing structured data. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Ruby Academy?
No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
How long does the “Practical Use Cases” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Ruby Academy lesson?
Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- case/in Basics
- Array and Hash Patterns
- Find Patterns and Guards
- Practical Use Cases