NoMatchingPatternError
RubyERRORCommonPattern Matching

Pattern matching found no match (Ruby 3.x)

Quick Answer

Use case/in with an else clause for safe matching; use => only when you are certain the pattern will match.

What this means

Raised by the one-line pattern matching operator => (pin operator) in Ruby 3.x when the pattern does not match and no else branch is present. Not raised by the case/in form which does not raise on no-match.

Why it happens
  1. 1Using the => deconstruct operator on data that does not match the expected pattern
  2. 2Receiving unexpected data shapes from external APIs in a pattern-matched pipeline

Fix 1

Use case/in with else for safe matching

Use case/in with else for safe matching
response = fetch_data

case response
in { status: 200, body: String => body }
  process(body)
in { status: Integer => code }
  handle_error(code)
else
  raise "Unexpected response shape: #{response.inspect}"
end

Why this works

case/in does not raise NoMatchingPatternError on no match — the else clause handles unexpected shapes explicitly.

Fix 2

Use find pattern for flexible matching (Ruby 3.0+)

Use find pattern for flexible matching (Ruby 3.0+)
# Find pattern [*, pattern, *] matches anywhere in an array
case data
in [*, { error: String => msg }, *]
  log_error(msg)
else
  # handle no error found
end

Why this works

The find pattern [*, ..., *] searches for a matching element anywhere in the array, avoiding position-dependent NoMatchingPatternError.

Code examples
Trigger with =>ruby
data = { code: 404 }
data => { code: 200 }  # NoMatchingPatternError: {:code=>404}
Safe formruby
{ code: 404 } in { code: 200 }  # returns false, does not raise
Same error in other languages
Sources
Official documentation ↗

Ruby Core Documentation — Pattern Matching

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors