0Pricing
Ruby Academy · Lesson

Find Patterns and Guards

Conditions in matches.

Guard Conditions

Add an if or unless guard to a pattern. The branch matches only when both the pattern and the condition succeed.

case 7
in Integer => n if n.odd?
  puts 'odd integer'
end

Guards Use Bound Variables

The guard can reference variables bound by the pattern, so you can express rich conditions about the matched data.

case [4, 9]
in [a, b] if a < b
  puts 'ascending pair'
end

All lessons in this course

  1. case/in Basics
  2. Array and Hash Patterns
  3. Find Patterns and Guards
  4. Practical Use Cases
← Back to Ruby Academy