Ruby Case/In Patterns
Case/in tries a value against a series of shape patterns. Each in clause checks the shape of the value and can pull parts of it out.
An array pattern checks types in order
The pair holds a number then a word. The first pattern checks both positions in order and matches.
pair = [3, "cat"]
case pair
in [Integer, String]
puts "number then word"
in [String, Integer]
puts "word then number"
else
puts "another shape"
endA hash pattern pulls values out
The hash pattern names item and count inside the hash. The clause body then prints both pulled values.
order = {item: "pen", count: 4}
case order
in {item:, count:}
puts item
puts count
else
puts "missing fields"
endA failed pattern falls to the next in
Three pairs run through the same case one at a time. Each pair lands on the first clause its shape satisfies.
shapes = [[1, 2], ["a", "b"], [true, false]]
shapes.each do |shape|
case shape
in [Integer, Integer]
puts "two numbers"
in [String, String]
puts "two words"
else
puts "other pair"
end
endA bare value matches by ==
The level is a plain number, so the clauses hold bare values. The clause whose value equals the level is the one that runs.
level = 3
case level
in 1
puts "easy"
in 3
puts "hard"
else
puts "unknown"
endExample
events = [[1, "click"], {kind: "hover", count: 2}, "reset"]
events.each do |event|
case event
in [Integer, String]
puts "numbered event"
in {kind: String, count: Integer}
puts "counted event"
in "reset"
puts "reset event"
end
endKey points
- An array pattern checks each position in order, including the class of each part.
- A hash pattern pulls named values out of a hash so the clause can use them.
- When a pattern fails, matching falls through to the next in clause.
- An in clause with a bare value matches by ==, like a plain comparison.
- A value that matches no clause and has no else raises an error.
In this example, each event meets the clauses in order and stops at the first shape it fits. The array event matches the pair pattern, the hash event matches the hash pattern, and the word matches the bare value by ==.
Note
The first matching clause wins, so clause order matters.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In a case/in statement, what happens when a pattern fails to match?