Whoa, haven’t seen this technique used much in Ruby. I think I’ve seen
some pattern matching in ES6. Seems like it’d be useful for massaging
and operating on nested data structures. Some kind of combination
between dig and variable assignment.
Let’s work through different uses of pattern matching using the
following list of maps:
Pattern matching lists
First and foremost, we gotta cut the crap by pattern matching like this:
Sweet, what happened here was we assigned ok, atcq, tp to the first
three items in hiphopheads. Then the pipe operator | was used to
assign all remaining items in the hiphopheads list to crap.
We must be mindful of pattern matching more items than we actually have
in the list, i.e., if we desired to pattern match ok, atcq, tp, crap, yo
again hiphopheads. Elixir would respond with with MatchError.
Pattern matching maps
What if we wanted to work with a specific group? Luckily, we can also
pattern match against maps. What’s happening below is ok["group"] is assigned to crew, and ok["name"] is assigned to nombre.
Combining pattern matching lists and maps together!!!!!
Holy shit this is pretty cool. Check this shit, gonna break it down step
by step. In this example below, we match the hiphopheads list to ok
and rest for a total of 2 pattern matches.
What if we further wanted to match the group key of the first match
ok against hiphopheads?
The upshot is we gotta give the = a little more respect. Aside from
assignment, we can also use it to pattern match. Really dope shit.