0Pricing
Ruby Academy · Lesson

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)
end

Handling 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

  1. case/in Basics
  2. Array and Hash Patterns
  3. Find Patterns and Guards
  4. Practical Use Cases
← Back to Ruby Academy