Created
September 8, 2018 16:54
-
-
Save pyrmont/06d5385adeca3934514afa4125fda8c2 to your computer and use it in GitHub Desktop.
Pattern Matching Syntax Examples
This file contains 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
# Current | |
case obj | |
when String | |
"String" | |
else | |
"Other" | |
end | |
# Deconstructing | |
case obj | |
when :ok, 42 | |
"42" | |
else | |
"Other" | |
end | |
# Deconstructing with implicit assignment | |
case obj | |
when :ok, x | |
"Result: #{x}" | |
else | |
"Other" | |
end | |
# Deconstructing with express assignment | |
case obj | |
when :ok, 42 as status, result | |
"Status: #{status}, Result: #{result}" | |
else | |
"Other" | |
end | |
# Deconstructing with implicit assignment and guard | |
case obj | |
when :ok, x if x < 100 | |
"Result: #{x}" | |
else | |
"Other" | |
end | |
# Deconstructing with pinning and express assignment | |
case obj | |
when :ok, ^x as _, result | |
"x: #{result}" | |
else | |
"Other" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment