Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 20 of 23 · Ruby 4.0

Match structured data

Select a branch using the shape and values of a Hash.

Learn

Pattern matching examines a value’s structure. In a case/in expression, a hash pattern can require particular keys and bind values to local variables. This is useful when handling data with several possible shapes.

The role value in the example must match "admin". The name: shorthand binds the associated value to a local variable named name. The else branch handles other shapes or values. Without a matching branch or else, case/in raises NoMatchingPatternError.

A hash pattern allows extra keys by default. Add **nil at the end of the pattern to reject extra keys. A guard such as if count > 0 checks a condition after the pattern has matched and bound its variables.

Example

user = { name: "Ruby", role: "admin" }
case user
in { name:, role: "admin" }
  puts "Welcome, #{name}"
else
  puts "Guest"
end

Experiment

  • Predict which inputs match. Add an admin hash with an extra key, then change the last hash to include role: "admin". Which pattern requirements must each input meet?

  • Predict whether this hash matches. Add **nil after count: in the pattern and compare, then remove the extra source key.

  • Predict the branch. Try count values 0 and 5, then remove the count key. Which check requires structure and which checks the bound value?

Explore the official manual

Ruby 4.0.0 · Example

Ready to run

Output

Run the code to see what happens.