Skip to content

Instantly share code, notes, and snippets.

@VorontsovIE
Forked from sherpc/defnil.rb
Last active December 16, 2015 11:29
Show Gist options
  • Save VorontsovIE/5427454 to your computer and use it in GitHub Desktop.
Save VorontsovIE/5427454 to your computer and use it in GitHub Desktop.
module DefNil
def defnil(meth)
self.class.class_eval do
alias_method "#{meth}_before_defnil", meth
define_method meth do |first_arg, *args, &block|
if first_arg
send("#{meth}_before_defnil", first_arg, *args, &block)
else
nil
end
end
end
end
end
extend DefNil
def f(x,y)
x + y
end
defnil :f
f(1,2) # => 3
f(nil,2) # => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment