Skip to content

Instantly share code, notes, and snippets.

@thiagofm
Created September 4, 2022 08:43
Show Gist options
  • Save thiagofm/965bad98e531b9f5e74545e56fa0bb5b to your computer and use it in GitHub Desktop.
Save thiagofm/965bad98e531b9f5e74545e56fa0bb5b to your computer and use it in GitHub Desktop.
Ruby Pattern Matching on Type
# Ruby pattern matching based on Type (=> operator)
[1,2,3] => [1, Integer, my_variable]
# This means:
# We want to assign `my_variable` (variable binding),
# but only if the first position is 1 and second position is an Integer)
my_variable # => 3 ✨
# What if it doesn't match? You get an exception 💣
[1,2,3] => [Integer, String, my_variable]
# [1, 2, 3]: String === 2 does not return true (NoMatchingPatternError)
# Ok, I get it, but what is a good usecase for this? 🤔
# You can use it enforce types on a response, while parsing it:
{name: "Yukihiro Matsumoto", age: 57} => {
name: String => name,
age: Integer => age,
}
name # => "Yukihiro Matsumoto"
age # => 57
# Did you notice the => operator on String => name?
# This means you are binding the value to a variable `name` (variable binding).
# Next tweets we'll go through more advanced usage and...
# Parsing any data structure using pattern matching, prepare to be mindblown🤯
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment