Intern Track Roadmap

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
Free preview · Lesson 1 4 min read

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 lessons
Type to start searching...