Skip to content

Instantly share code, notes, and snippets.

@VorontsovIE
Forked from sherpc/defnil.clj
Last active December 16, 2015 11:29
Show Gist options
  • Save VorontsovIE/5427559 to your computer and use it in GitHub Desktop.
Save VorontsovIE/5427559 to your computer and use it in GitHub Desktop.
# Если ты создаешь новую функцию, а не меняешь старую, то всё проще, конечно.
def nillified(&block)
->(first_arg, *args) {
first_arg ? block.call(first_arg, *args) : nil
}
end
f = nillified{|x,y| x + y }
f.call(1,2)
f.call(nil,2)
# Здесь конечно играет роль, что лямбды вызываются не так же как функции и приходится юзать call
# А вот так чуть-чуть длиннее, зато создается метод но это особо не влияет
def defnil(meth_name, &block)
define_method meth_name, &->(first_arg, *args) {
first_arg ? block.call(first_arg, *args) : nil
}
end
defnil(:g){|x,y| x + y }
g(1,2)
g(nil,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment