Image of Lucian Ghinda writing for notes.ghinda.com
November 21st, 2024

Using Pattern Matching in Ruby to act based on array contents

The following piece of code is inspired by something I wrote the other day. I cannot share the exact piece of code or the content, but I liked the syntax so I played a bit with it here. 

Matching against array being empty or not 

You can use in [] to match if the array is empty. And you can use in [*] to match when an array has elements. 

You can combine in with if and have something like: in [*] if <condition>

Example of using pattern matching to check empty/non-empty arrays
Example of using pattern matching to check empty/non-empty arrays

Please note the results of using in [] and in [*] with empty

Remember that [] in [] will return true and use case in with checking about empty first:

Checking about being empty first
Checking about being empty first

Using pattern matching with values of elements inside the array

Pattern matching can also be used in this way: to check if there are any elements with 0 or nil values inside the array:

Checking if any elements are of a specific type and values
Checking if any elements are of a specific type and values