Pattern Matching in Ruby
Use Ruby's modern pattern matching with case/in to destructure and match complex data structures.
Introduction to Pattern Matching
Ruby 3.0+ introduced pattern matching using case/in. It lets you match a value against a pattern and destructure it in one step — more expressive than traditional if/else chains.
1. Basic case/in Example
Match a value against fixed patterns.
2. case/in vs case/when
Understand the difference.
Literal & OR Patterns
You can match exact literal values (integers, strings, symbols, booleans, nil) and combine them using the | operator.
1. Literal Pattern
Match exact values.
2. OR Pattern (|)
Match multiple alternative values.
Array Patterns
Ruby pattern matching can match arrays by structure, extracting values into variables at the same time.
1. Fixed-Length Array Pattern
Match exact structure.
2. Variable-Length Array Pattern (*)
Capture remaining elements with splat.
3. Typed Array Pattern
Match elements by type.
Hash Patterns
Pattern matching on hashes allows you to match specific keys and extract their values. Extra keys are ignored by default.
1. Matching Hash Keys
Match required keys and extract values.
2. Hash Shorthand Binding
Bind value to key name automatically.
Guard Conditions
Guards let you add an if condition after the pattern to further restrict when a case matches.
1. Pattern with Guard
Add condition after pattern.
2. Guard on Hash Pattern
Combine hash match with condition.
Find Pattern
The find pattern [*, pattern, *] lets you search inside an array for an element that matches, without knowing its position.
1. Find Pattern Basics
Match anywhere inside an array.
2. Find Pattern with Hashes
Find a matching hash inside an array.
Real-World Use Cases
Pattern matching simplifies parsing commands, handling API responses, and processing structured data like JSON.
1. Command Parser
Parse command arrays cleanly.
2. API Response Handling
Match response structure.
3. Custom Classes with deconstruct_keys
Make custom objects pattern-matchable.