Skip to content

Instantly share code, notes, and snippets.

@thiagofm
Created September 5, 2022 11:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagofm/757ede0cfcc2ea750c45747372defcc8 to your computer and use it in GitHub Desktop.
Save thiagofm/757ede0cfcc2ea750c45747372defcc8 to your computer and use it in GitHub Desktop.
Pattern Matching Magic
# 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