Pattern matching selects behavior by testing a value against a declared pattern. In Ruby, regular expressions match character patterns in strings, supporting branching, substring extraction, scanning, substitution, and splitting. Ruby also uses case...in to match an object's structural shape rather than merely testing a condition. section 11.0 section 16.3.1
Structural patterns can distinguish an empty array, a one-element array, a two-element array, or a longer array. Captures bind parts of a successful match, such as a head element and the remaining tail. Patterns can also constrain types, as with Numeric, and combine matching with guards or ranges. section 16.3.1
def describe_array_as_list(xs)
case xs
in []
"empty"
in [x]
"one element: #{x}"
in [x,y]
"two elements: #{x} and #{y}"
in [x, *rest]
"head: #{x}, tail: #{rest.inspect}"
end
end
This example widens from fixed array shapes to a rest pattern, showing how matching can classify a value and extract its components in one operation. section 16.3.1
Selecting with patterns
Enumerable#grep applies the case-equality operator (===) to each element. Thus colors.grep(/o/) selects strings containing “o”, miscellany.grep(String) selects strings, and miscellany.grep(50..100) selects values inside the range. A block can transform the selected results. section 10.3.3
Pattern matching supports several related tasks:
- Branch on whether text matches a regular expression. section 11.0
- Locate substrings or process repeated occurrences within a string. section 11.1
- Select enumerable elements through regular expressions, classes, ranges, or other expressions implementing ===. section 10.3.3











