Last active
September 14, 2022 20:21
-
-
Save henrik/e552646d96d6092f58f523306c9eeb67 to your computer and use it in GitHub Desktop.
A for-fun vaguely Elixir-style guard clause proof-of-concept in Ruby. Probably not a good idea… https://twitter.com/henrik/status/1570145637920026624
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
class Object | |
def guard(cond, meth) | |
prepend(Module.new { | |
define_method(meth) { |*a, **aa, &b| | |
super(*a, **aa, &b) if send(cond, *a, *aa, &b) | |
} | |
}) | |
end | |
end | |
class Foo | |
guard :even?, | |
def hi(number) | |
puts "Hi #{number}!" | |
end | |
private | |
def even?(num) = num.even? | |
end | |
Foo.new.hi(1) # No output. | |
Foo.new.hi(2) # Output. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment