Last active
March 27, 2024 12:33
-
-
Save rickychilcott/4eb32f688de5a19c79396580a5fa52e7 to your computer and use it in GitHub Desktop.
Ruby Pattern Matching Shenanigans
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
def example(label) | |
puts "## #{label}" | |
yield | |
puts | |
puts | |
end | |
example("Foo.===(v)") do | |
class Foo | |
def self.===(v) | |
puts "Foo.===" | |
v == "hello" | |
end | |
end | |
case "hello" | |
in Foo | |
puts "Foo" | |
else | |
puts "Not Foo" | |
end | |
end | |
example("Foo#===(v)") do | |
class Foo | |
def ===(v) | |
puts "Foo#===" | |
v == "hello" | |
end | |
end | |
case "hello" | |
when Foo.new | |
puts "Foo" | |
else | |
puts "Not Foo" | |
end | |
end | |
example("Proc-based") do | |
case "hello" | |
in ->(x) { | |
puts "Proc" | |
true | |
} | |
puts "Foo" | |
else | |
puts "Not Foo" | |
end | |
end | |
example("Override Object and match per pattern") do | |
class Object | |
def in(pattern) | |
puts "in" | |
pattern === self | |
end | |
end | |
if "hello".in(Foo.new) | |
puts "Foo" | |
elsif "hello".in(Foo) | |
puts "Foo" | |
else | |
puts "Not Foo" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment