Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active September 14, 2022 20:21
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 henrik/e552646d96d6092f58f523306c9eeb67 to your computer and use it in GitHub Desktop.
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
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