2024-02-23 Ruby Pattern Matching
Ruby v3.0でパターンマッチが導入された。
使い方をメモ。
型にマッチ
case { name: 'taro', age: 20 }
in { name: String, age: Integer } then true
end
#=> true
マッチしなかった場合に例外
case { name: 'taro' }
in { name: String, age: Integer } then true
end
#=> key not found: :age (NoMatchingPatternKeyError)
else
をつければ例外じゃなくなる。
case { name: 'taro' }
in { name: String, age: Integer } then true
else false
end
#=> false
一行でマッチ判定
{ name: 'taro', age: 1 } in { name: String, age: Integer }
#=> true
{ name: 'taro' } in { name: String, age: Integer }
#=> false
| で複数のパターンを指定
case {key: 'a'}
in {key: 'a' | 'b'}
puts "key is 'a' or 'b'"
else
puts "key is not 'a' or 'b'"
end
# key is 'a' or 'b'
数値範囲
case {name: "Alice", age: 30}
in {age: 30..}
puts "Age is 30 or older"
in {age: 0..29}
puts "Age is under 30"
end
# Age is 30 or older
値取り出し
case {a: 1, b: 2, c: 3}
in {a:, b:}
puts "a is #{a}, b is #{b}"
end
# a is 1, b is 2