Ruby logic: pattern matching (case/in)
Ruby's case/in, called pattern matching, checks whether a value has a certain shape and pulls its pieces out in the same step. The lessons cover array patterns with fixed slots, _, nesting, splats and the find pattern. Hash patterns match by key and ignore extra keys unless **nil is used. Guards with if and unless, the pin operator ^, alternatives with |, ranges and => captures come next. The last lessons compare case/in with case/when, show the one-line in and => forms, and end with a small challenge.
What you'll learn
- ✓Matching arrays by shape with _, nested patterns, splats and the find pattern
- ✓Matching hashes by key, requiring values, and using **nil and **rest
- ✓Adding if and unless guards, and comparing against existing values with ^
- ✓Accepting several patterns with | and capturing the match with =>
- ✓How case/in differs from case/when, including NoMatchingPatternError
- ✓One-line matching with value in pattern and value => pattern
Beyond when: introducing case/in
The previous course, "Ruby logic: standard checks", ended with case/when. It answers one kind of question well: which of these possibilities does this single value match? grade_letter and day_type both checked one value against a list.
Read the full lesson free →Curriculum
7 lessonsBeyond when: introducing case/in
Introduces case/in as a way to check a value's shape and bind its pieces to variables.
Matching array structure
Covers fixed-length array patterns, ignoring positions with _, nested patterns, splats and the find pattern.
Matching hash structure
Shows hash patterns that match by key, ignore extra keys, require values and need Symbol keys.
Guards and the pin operator
Adds if and unless guards to patterns and uses ^ to compare against an existing value.
Alternatives, ranges and =>
Explains alternatives with |, comparison with ===, endless ranges, the no-capture rule and binding with =>.
case/in vs case/when, and one-line matching
Compares case/in with case/when, covers NoMatchingPatternError, and introduces the one-line in and => forms.
Putting it together: a small challenge
Reads a classifier that combines the course's patterns, then sets a challenge to write describe_result.