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.
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.
- 1Using the => deconstruct operator on data that does not match the expected pattern
- 2Receiving unexpected data shapes from external APIs in a pattern-matched pipeline
Fix 1
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}"
endWhy 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+)
# Find pattern [*, pattern, *] matches anywhere in an array
case data
in [*, { error: String => msg }, *]
log_error(msg)
else
# handle no error found
endWhy this works
The find pattern [*, ..., *] searches for a matching element anywhere in the array, avoiding position-dependent NoMatchingPatternError.
data = { code: 404 }
data => { code: 200 } # NoMatchingPatternError: {:code=>404}{ code: 404 } in { code: 200 } # returns false, does not raiseRuby Core Documentation — Pattern Matching
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev