Pattern matching
case-in
Pattern matching tests the shape of a value with case and in instead of a chain of conditions.
When the hash has the expected keys, the code after in runs with the extracted parts.
value = { status: "ok", code: 200 }
case value
in { status: "ok", code: code }
puts "OK: #{code}"
else
puts "Other"
end
ruby case_demo.rb
OK: 200
Bind variables
Patterns can bind parts of a value to new variables for the branch body.
First takes the head of the array while rest collects the remaining elements.
case [1, 2, 3]
in [first, *rest]
puts first
p rest
end
ruby bind_demo.rb
1
[2, 3]
Match arrays
Array patterns match element by element, mixing exact values with captures and wildcards.
200 with a message prints the message, while a bare star swallows any tail.
case [200, "OK"]
in [200, message]
puts message
in [404, *]
puts "Missing"
else
puts "Other"
end
ruby array_demo.rb
OK
Match hashes
Hash patterns match by key and can check value types while binding results.
The String check guarantees a real name, and the admin literal restricts the role.
user = { name: "Ada", role: "admin" }
case user
in { name: String => name, role: "admin" }
puts "Admin #{name}"
else
puts "Guest"
end
ruby hash_demo.rb
Admin Ada
Next: Modern Ruby tour
Article author: Arthur Isaev