GAURAV VARMA
Ruby 2.7 introduces pattern matching as an experimental feature — a powerful new control flow tool that brings deconstruction and deep matching to your Ruby code.
What is Pattern Matching?
Pattern matching allows you to match against the structure of objects (arrays, hashes, or custom types) and extract values inline. It uses the new case in syntax to provide clean and expressive matching logic.
Basic Example
1case [0, 1, 2]
2in [0, x, y]
3 puts "x = #{x}, y = #{y}"
4endThis pattern matches the array [0, 1, 2] and destructures it: x = 1, y = 2.
Matching Hashes and Object Types
You can use type guards with destructuring:
1case { name: "Alice", age: 30 }
2in { name: String => name, age: Integer => age }
3 puts "#{name} is #{age}"
4endThis matches the hash shape, confirms the types, and binds values.
Find Pattern Support
In Ruby 2.7 and beyond, you can match an element within a larger array using the splat (*) syntax:
1json = { name: "John", friends: [{ name: "Alex", age: 24 }, { name: "Don", age: 25 }] }
2
3case json
4in { name: "John", friends: [*, { name: "Alex", age: age }, *] }
5 puts "Alex is #{age}"
6endThis works even if the element appears in the middle of the array — thanks to the find pattern.
Complex Matching with Arrays
You can match parts of arrays with trailing or leading elements using the splat operator:
1case ["alpha", 1, "beta", "gamma", 2, "a", "b", "c", 3]
2in [*pre, String => x, String => y, *post]
3 p pre # => ["alpha", 1]
4 p x # => "beta"
5 p y # => "gamma"
6 p post # => [2, "a", "b", "c", 3]
7endThis elegantly extracts the first matching sequence of two strings while capturing what's before and after.
When to Use It
Pattern matching is great for:
- Cleaning up deeply nested
if/casechains - Extracting values from API responses
- Handling structured JSON-like data
Caveats
- Pattern matching is experimental in Ruby 2.7 — syntax and behavior may evolve
- Only available via
case insyntax (no standaloneinblocks) - Not all Ruby types and structures support pattern matching natively yet
Resources
Summary
Pattern matching in Ruby 2.7 opens the door to cleaner, safer, and more expressive control flow — especially when dealing with structured data. While still evolving, it's a game-changing addition worth exploring in your apps and experiments.