liveBook · Manning

Pattern matching

As explained in The Well-Grounded Rubyist, Fourth Edition

Pattern matching is a technique for selecting behavior by testing the structural shape and contents of a value against declarative patterns.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains regular-expression applications, structural captures, type constraints, guards, and grep's reliance on ===.
Examples
Demonstrates array-shape descriptions, grade calculation, regular-expression selection, class selection, and range selection.
What it assumes
Assumes basic Ruby objects, strings, arrays, and enumerable operations while developing regular-expression and structural-matching literacy.
What you can do after
Apply pattern matching through Ruby regular expressions, case...in statements, and Enumerable#grep.
How it connects
Connects regular expressions with strings, case...in with functional programming, and grep with Enumerable and case equality.

Also explained in

Compare how 12 books explain pattern matching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.