-
-
Save VorontsovIE/5427559 to your computer and use it in GitHub Desktop.
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
# Если ты создаешь новую функцию, а не меняешь старую, то всё проще, конечно. | |
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