Practical Use Cases
Parsing structured data.
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' }))All lessons in this course
- case/in Basics
- Array and Hash Patterns
- Find Patterns and Guards
- Practical Use Cases