Introduction to Pattern Matching in Ruby 3.0

Introduction to Pattern Matching in Ruby 3.0

Ruby 3.0 introduces a new feature called pattern matching, which allows you to match values against patterns and extract data from structures. This can be a powerful tool for simplifying complex conditional logic and making your code more readable.

How Pattern Matching Works in Ruby

To use pattern matching in Ruby, you can use the case statement and a keyword. Here is an example of how pattern matching works in Ruby:


def greet(person)
  case person
  in { name: "Alice", age: 18 }
    puts "Hello, Alice! You are 18 years old."
  in { name: "Bob", age: age }
    puts "Hello, Bob! You are #{age} years old."
  in { name: name }
    puts "Hello, #{name}! I don't know your age."
  end
end

greet(name: "Alice", age: 18)  # Outputs: "Hello, Alice! You are 18 years old."
greet(name: "Bob", age: 35)    # Outputs: "Hello, Bob! You are 35 years old."
greet(name: "Charlie")          # Outputs: "Hello, Charlie! I don't know your age."        

In this example, we have defined a 'greet' method that uses pattern matching to determine how to greet a person based on their name and age. The case statement allows us to match the person object against different patterns, and the in keyword allows us to specify the pattern we want to match.

In the first pattern, we match a person with the name "Alice" and the age 18. If the person object matches this pattern, we output a greeting for Alice. In the second pattern, we match a person with the name "Bob" and any age. If the person object matches this pattern, we output a greeting for Bob and include the person's age in the greeting. In the third pattern, we are matching any person with a name. If the person object matches this pattern, we output a generic greeting without mentioning the person's age.

Using Pattern Matching with Data Structures

Pattern matching is beneficial when working with #datastructures, such as hashes and arrays, where you may want to extract specific values based on certain patterns. Here is an example of how you can use pattern matching with data structures:

def process_request(request)
  case request
  in { method: "GET", path: "/" }
    # handle GET request to the root path
  in { method: "POST", path: "/users", body: { name: name, email: email } }
    # handle POST request to create a new user with the given name and email
  in { method: method, path: path }
    # handle any other request with the given method and path
  end
end

process_request(method: "GET", path: "/")         # matches first pattern
process_request(method: "POST", path: "/users", body: { name: "Alice", email: "alice@example.com" })  # matches second pattern
process_request(method: "PUT", path: "/users/123") # matches third pattern        

In this example, we have defined a process_request method that uses pattern matching to handle different types of HTTP requests. The case statement allows us to match the request object against different patterns, and the in keyword allows us to specify the pattern we want to match.

In the first pattern, we are matching a GET request to the root path. If the request object matches this pattern, we handle the request appropriately. In the second pattern, we are matching a POST request to the /users path with a specific body structure. If the request object matches this pattern, we handle the request by creating a new user with the given name and email. In the third pattern, we are matching any request with a specific method and path. If the request object matches this pattern, we handle the request appropriately.

As you can see, pattern matching can be a very useful tool for handling different types of requests in a flexible and readable way. It allows you to specify specific patterns to match against and extract specific values from the request object as needed.

Conclusion

Pattern matching is a powerful new feature in Ruby 3.0 #ruby that can help you simplify complex conditional logic and make your code more readable. It is particularly useful when working with data structures, and can be a useful tool for handling different types of requests and extracting specific values from structures.

I hope this article has helped to introduce you to pattern matching in Ruby 3.0 and show you how it can be used in your code.

Reference Links

- [Ruby 3.0 documentation on pattern matching](https://ruby-doc.org/core-3.0.0/doc/syntax/pattern_matching_rdoc.html)

- [Blog post on pattern matching in Ruby 3.0](https://blog.bigbinary.com/2020/12/16/ruby-3-0-brings-pattern-matching.html)

- [Video tutorial on pattern matching in Ruby 3.0](https://www.youtube.com/watch?v=vYpT-KjZFto)

To view or add a comment, sign in

More articles by Atish Maske

  • How Apache Lucene Makes Searching Super Fast

    Today, I want to talk about something really cool: how Apache Lucene stores and retrieves data so efficiently. We’re…

    1 Comment
  • Ruby Hooks: Extending Class Functionality with the included Hook

    Introduction In the world of Ruby programming, we often rely heavily on Rails due to its abundant support and…

  • How to Use Multiple GitHub Accounts

    If you have multiple GitHub accounts, it can be a challenge to manage them on the same computer. Fortunately, with a…

    10 Comments
  • Design Patterns - Strategy Pattern

    Introduction to Design Patterns In software engineering, a design pattern is a reusable solution to a common problem in…

Others also viewed

Explore content categories