Ruby Logo

Pattern Matching (case/in)

Master Ruby 2.7+ pattern matching with case/in statements, array/hash patterns, object patterns, and guard clauses.

Home Ruby Pattern Matching (case/in)
'); opacity: 0.3;">

Pattern Matching

Ruby 2.7's game-changing feature for elegant data destructuring and structural matching

Ruby 2.7+case/in statements

Why Pattern Matching Matters

Transform how you handle complex data structures and API responses

BEFORE

Traditional Approach

# Nested if/else hell
if data.is_a?(Hash)
  if data[:type] == "user"
    if data[:profile]
      name = data[:profile][:name]
    end
  end
end
AFTER

Pattern Matching

# Clean, declarative matching
case data
in { type: "user", profile: { name: } }
  puts "Hello, #{name}!"
end

Structural Matching

Match against data shapes and extract values in one step. No more nested conditionals.

Variable Binding

Automatically extract and bind values from matched patterns into local variables.

Guard Clauses

Add conditional logic to patterns for precise matching and validation.

Syntax & Fundamentals

SYNTAX Basic Pattern Matching

# Basic case/in pattern matching
def process_data(data)
  case data
  in Integer => num
    "Number: #{num}"
  in String => str
    "Text: #{str}"
  in Array => arr
    "List with #{arr.size} items"
  else
    "Unknown type"
  end
end

ARRAYS Array Destructuring

# Array pattern matching
case [1, 2, 3]
in [first, *rest]
  "First: #{first}, Rest: #{rest}"
end

case ["user", 123, "admin"]
in ["user", id, role]
  "User #{id} has role #{role}"
end

Real-World Use Cases

Practical applications that solve everyday programming challenges

API Response Processing

Handle complex JSON responses with elegant pattern matching

# Processing GitHub API responses
def process_github_event(event)
  case event
  in { type: "push", payload: { commits: commits, ref: } }
    "#{commits.size} commits pushed to #{ref}"

  in { type: "pull_request", payload: { action: "opened", pull_request: { title: } } }
    "New PR: #{title}"

  in { type: "issues", payload: { action: "closed", issue: { number: issue_num } } }
    "Issue ##{issue_num} closed"

  else
    "Unhandled event: #{event[:type]}"
  end
end

Configuration Parsing

Validate and extract configuration values with type safety

# Database configuration validation
def setup_database(config)
  case config
  in { adapter: "postgresql", host:, database:, username:, password: }
    PostgreSQL.connect(host:, database:, username:, password:)

  in { adapter: "sqlite", path: }
    SQLite.connect(path)

  in { adapter: adapter }
    raise "Unsupported adapter: #{adapter}"

  else
    raise "Invalid database configuration"
  end
end

Advanced Patterns & Techniques

ADVANCED Guard Clauses

# Pattern matching with conditions
case user_data
in { age: age, status: "active" } if age >= 18
  "Adult active user"

in { age: age, status: "active" } if age < 18
  "Minor active user"

in { scores: [*scores] } if scores.all? { _1 > 80 }
  "Excellent performance!"
end

OBJECTS Custom Object Matching

# Match custom objects
class User
  attr_reader :name, :email, :role
end

case user
in User[name: "admin", role: "admin"]
  "Admin user detected"

in User[name:, email: /@company\.com$/]
  "Company employee: #{name}"
end

Best Practices & Guidelines

Write maintainable and performant pattern matching code

DO

Use for Complex Structures

  • Destructure nested data structures
  • Extract values in one step
  • Handle API responses and configs
  • Replace deeply nested if/else
DON'T

Overuse for Simple Cases

  • Simple equality checks
  • Single value comparisons
  • Basic type checking
  • Performance-critical loops
TIP

Performance Considerations

  • Patterns are evaluated top-to-bottom
  • Put specific patterns first
  • Use guard clauses sparingly
  • Consider caching for hot paths

Ready to Transform Your Code?

Pattern matching makes complex data handling elegant and maintainable

Start Simple

Begin with basic type matching and value extraction

Refactor APIs

Replace nested conditionals in API response handlers

Master Guards

Add conditional logic for precise pattern matching

Build DSLs

Create elegant domain-specific languages

Quick Navigation

Related Topics

Video Tutorial

Watch and learn pattern matching (case/in)

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!