Skip to content

Instantly share code, notes, and snippets.

@rickychilcott
Last active March 27, 2024 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickychilcott/4eb32f688de5a19c79396580a5fa52e7 to your computer and use it in GitHub Desktop.
Save rickychilcott/4eb32f688de5a19c79396580a5fa52e7 to your computer and use it in GitHub Desktop.
Ruby Pattern Matching Shenanigans
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