Pattern matching cho phép destructure và match cấu trúc dữ liệu trong một bước — tương tự Elixir/Rust nhưng có cú pháp Ruby.
ruby
# case/in — matching cấu trúc
response = { status: 200, body: { user: { name: "Alice", role: :admin } } }
case response
in { status: 200, body: { user: { name: String => name, role: :admin } } }
puts "Admin: #{name}" # => Admin: Alice
in { status: 404 }
puts "Not found"
end
# Find pattern — tìm phần tử trong mảng
case [1, 2, "hello", 3, 4]
in [*, String => s, *]
puts "Found string: #{s}" # => Found string: hello
end
# Pin operator ^ — so sánh với biến đã biết
expected = 42
case { value: 42 }
in { value: ^expected }
puts "matched!" # => matched!
endRuby 3.0: experimental; Ruby 3.1+: stable.
Hữu ích khi parse JSON response, xử lý event có cấu trúc.
Pattern matching enables destructuring and matching data structures in one step — similar to Elixir/Rust but with Ruby syntax.
ruby
response = { status: 200, body: { user: { name: "Alice", role: :admin } } }
case response
in { status: 200, body: { user: { name: String => name, role: :admin } } }
puts "Admin: #{name}" # => Admin: Alice
in { status: 404 }
puts "Not found"
end
# Find pattern
case [1, 2, "hello", 3, 4]
in [*, String => s, *]
puts "Found string: #{s}"
end
# Pin operator
expected = 42
case { value: 42 }
in { value: ^expected }
puts "matched!"
endRuby 3.0: experimental; Ruby 3.1+: stable.
Useful for parsing JSON responses, processing structured events.