0Pricing
Ruby Academy · Lesson

Practical Use Cases

Parsing structured data.

Practical Use Cases is a free Ruby Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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' }))

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

Tagged 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}")
end

Matching 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}")
end

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

Safe 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}")
end

Quick 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_keys for custom objects
  • Always add else for 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)
end

Frequently asked questions

Is the “Practical Use Cases” lesson free?

Yes — the full text of “Practical Use Cases” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

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

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