Created
September 5, 2022 11:11
-
-
Save thiagofm/757ede0cfcc2ea750c45747372defcc8 to your computer and use it in GitHub Desktop.
Pattern Matching Magic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Creating a complex hash, with nested keys | |
my_complex_hash = { | |
users: [ | |
{name: "Yukihiro Matsumoto", age: 57}, | |
{name: "Kabosu the Shiba Inu", age: 16}, | |
{name: "Thiago Massa", age: 33} | |
] | |
} | |
# What if we want to find the age of Matz? | |
my_complex_hash => { | |
users: [*_, {name: "Yukihiro Matsumoto", age: matz_age}, *_] | |
} | |
matz_age # => 57 | |
# 😱 WTF! What happened there? | |
# The _ just means we want to ignore the output and not want to assign it to a variable. | |
# We are using the Find pattern. (experimental feature on Ruby 3.1) | |
# By specifying *_ in the beginning and end we can search through the data structure... | |
# Similar to a Regexp! 🤯 So cool! | |
# Coming next we'll look into variable pinning in Pattern Matching 😊 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment