Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Functional languages have a powerful feature called pattern matching. Pattern matching is a tool that allows the user to check and extract a specific pattern from data structures like strings, arrays, etc. Ruby also supports pattern matching. Thus it enables the developers to write concise and expressive code with a simple syntax.
In this blog, we will discuss the concept of pattern matching in Ruby in detail. So without any further wait, let’s start learning!
Pattern Matching
Pattern Matching is a very common feature found in most functional languages like Scala. As the name suggests, it is a process of matching patterns. It is used to check whether a pattern is present in provided huge amount of data. It is important to note that it checks for an exact match, and thus the patterns should be identical. It allows users to write clean and concise code.
A few common examples of pattern matching are:
Email address validation
IP address validation
URL parsing
Pattern Matching in Ruby
Pattern matching was introduced in Ruby 2.7 and improved in the 3.1 version. In Ruby, pattern matching is done using the case statement. The case statement first checks the expression and then matches it against a series of patterns/options. It is similar to normal case statements. So what’s the difference? The answer to this is that instead of the when keyword, we use the in keyword.
Let us understand this using an example:
Normal Case Statement
value = 2
case value
when 1
puts "one"
when 2
puts "two"
when 3
puts "three"
else
puts "more than three"
end
You can also try this code with Online Ruby Compiler
In the normal case statement, the when clause checks if the value is 2 and likewise prints the result. But in the case of pattern matching case statements, the in keyword does the same job for us.
Types of pattern
Below are the various types of patterns which are available in Ruby.
Literal pattern
Variable pattern
Array pattern
Hash pattern
Lets us now look at each type of pattern in detail.
Literal Pattern
In Ruby, we can use literal values like strings, numbers, etc, as patterns. Let us look at an example to understand it better.
Example
def check(val)
case val
in String
puts "String value"
in Integer
puts "Integer value"
end
end
#First call
value = 'Coding'
check(value)
#Second call
value = 20
check(value)
You can also try this code with Online Ruby Compiler
In the above example, we created a check() function to check whether a literal is a string or an integer. We can clearly see that whenever we pass a string value or an integer value, the function prints the appropriate results.
Variable Pattern
This type of pattern is used to match the value and then assign it to the variable provided.
Example
name = 'Alice'
case name
in x
puts "The value in x is #{x}"
end
You can also try this code with Online Ruby Compiler
In the above example, we used the variable x to match the name variable. Here the name variable’s value gets assigned to the variable x, and the message is displayed.
Array Pattern
The array pattern is used to match an array against a pattern.
Example
case [3, 1, 3]
in [3, 1, 3]
puts "Its a match"
else
puts "No match"
end
You can also try this code with Online Ruby Compiler
In the above example, we matched the array with an exact pattern and got a match result.
Similarly, we can use a variable or the splat (\*) symbol to act as a placeholder for single or multiple entries. Let’s look at the example for them.
Example
#Single missing entry
case [3, 1, 3]
in [3, val, 3]
puts "Match 1"
else
puts "No match"
end
#Multiple missing entry
case [3, 1, 3]
in [3, *]
puts "Match 2"
else
puts "No match"
end
You can also try this code with Online Ruby Compiler
In the first case, the variable val act as a placeholder for a single missing entry. Similarly, we can use multiple variables to match multiple missing entries. But this can be avoided using the splat(\*) symbol, which is used to match multiple entries.
Hash Pattern
The hash pattern is used to match the specific key-value pair.
Example
case { name: 'sohail', age: 22 }
in { name: 'sohail', age: 22 }
puts 'match'
else
puts 'no match'
end
You can also try this code with Online Ruby Compiler
Here we used the key-value pair in the case statement and found its match using the in keyword.
Now, let’s understand some important concepts used in pattern matching in ruby.
Underscore Operator
In pattern matching, the underscore (‘_’) symbol is used to skip or ignore values. We use this operator as a wildcard whenever we don’t care about the pattern and just want to skip it.
Example
case ["Coding", "Ninjas"]
in _,_
puts "Pattern matched!"
else
puts "Pattern not matched!"
end
You can also try this code with Online Ruby Compiler
In the above example, we got the output pattern matched as the first underscore skips the first and the second underscore skips the second string, and the condition is satisfied.
Alternative match
The alternative match is used to match against multiple patterns. You can consider it as the OR operator, which executes even if either of the pattern matches.
Example
case 'D'
in 'A' | 'B'
puts "Grade is either A or B"
in 'C' | 'D'
puts "Grade is either C or D"
else
puts "Grade is below D"
end
You can also try this code with Online Ruby Compiler
Here the '|' symbol is used to check for alternative patterns. The match occurs when either pattern is the same.
Pattern Guard
The pattern guards are used to add some conditions for your match. You can consider it as the if keyword with some condition which is checked before matching the pattern.
Example
#Sum with more than value 10
sum = 15
case sum
in sum if sum > 10
puts 'Match'
else
puts 'No match'
end
#Decrementing the sum
sum = 5
case sum
in sum if sum>10
puts "Match"
else
puts "No match"
end
You can also try this code with Online Ruby Compiler
In the above example, we used the if keyword to check if the sum is more than ten. If it is, then only the match condition is checked; else, it prints no match.
Use Cases of Pattern Matching
Below are some use of pattern matching in Ruby.
It can extract patterns from various data structures. Thus it is useful while working with APIs with complex data structures.
We can use pattern Guard to simplify the cases by adding conditions to the cases.
Case statements in Ruby allow you to write more readable and concise code.
It is also used to handle exceptions by matching exceptions with some specific pattern.
Many text editors and IDEs use pattern matching for the implementation of syntax highlighting.
Frequently Asked Questions
What is pattern matching in Ruby?
In Ruby, pattern matching is a feature which allows you to extract and match some specific patterns within data structures.
What are the different pattern types in Ruby?
In Ruby, there are various pattern types, such as literal, variable, array, and hash patterns.
Is pattern matching compatible with older versions of Ruby?
No, pattern matching is the latest feature in Ruby, which is compatible with Ruby 2.7 and higher versions only.
How to match patterns in Ruby?
We can match any patterns in Ruby using the case statement along with the in keyword together.
Conclusion
This article discusses the concept of pattern matching in Ruby. We discussed various types of patterns along with their examples in detail. We hope this blog has helped you enhance your knowledge of pattern matching in Ruby. If you want to learn more, then check out our articles.
But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundles for placement preparations.
However, you may consider our paid courses to give your career an edge over others!