Pattern Matching (case/in) (Ruby)

Pattern matching, added in Ruby 3.0, uses case/in to destructure and match data structures by shape. It can deconstruct arrays and hashes, bind variables, and add guards in one expression.

Ruby

Distinct from the classic case/when (which tests with ===), the newer case/in matches a value against structural patterns. It can match array shapes ([a, b, *rest]), hash shapes ({name:, age:}), types (Integer => n), and combine them, binding the matched parts to variables.

Patterns support guards (in [x, y] if x > y), alternatives (in 1 | 2 | 3), and pinning (^value) to match against an existing variable's value. A find pattern can locate a sub-sequence. This makes parsing structured data — JSON, API responses, ASTs — clean and declarative.

case/in raises NoMatchingPatternError if nothing matches (use an in else or a final catch-all). It brings to Ruby the kind of structural matching familiar from Rust, Scala, and Elixir.

Syntax

case data
in [first, *rest]
  ...
in { name:, age: }
  ...
end

Examples

Ruby

data = { name: "Ada", role: :admin }
result = case data
in { name: String => n, role: :admin }
  "admin #{n}"
in { name: String => n }
  "user #{n}"
end
puts result

Output:

admin Ada

Learn it in a lesson

See also

Back to the Dictionary