The most important feature that was released in Ruby 2.7 was Pattern Matching. This feature is common in most functional programming languages such as Scala, Elixir, etc.
In Ruby, Pattern matching is the way to recognize a pattern of data
and execute some actions if the data matches the pattern.
Pattern matching in Ruby is performed using the case
statement
wherein the keyword in
is used instead of when
to match patterns.
An example of pattern matching in Ruby,
This feature was introduced in 2.7 and the Ruby community loves this feature as it makes the code more readable. Rails will now allow the same pattern matching feature against ActiveModel (also ActiveRecord) objects.
To understand how this could help the Rails codebase, let’s take an example of a User model with the following attributes-
- type
- preferred_full_name
- first_name
- last_name
We need to define a method to get a User’s full name but with the following conditions
- If
type
is “Employer”, then return “Name not required” - If
type
is “Employee” andpreferred_full_name
is given then return thepreferred_full_name
- If
type
is “Employee” andfirst_name
andlast_name
is given, then return the full name withfirst_name
and thelast_name
- If none of these scenarios are matched, return “Name not found”
Before
Before it’s latest version, the following code was used to create this method-
After
After the latest Rails version is released, the above method can become more readable using Pattern Matching.
The above method makes the code more readable and easy to understand. This enhancement helps a lot in writing methods with complex logic much easier.
Note: The enhancement is yet to be released in the official Rails version
Check out the PR for more details.