Last active
November 14, 2018 20:21
-
-
Save virtualstaticvoid/519e564c4ce653ec4817 to your computer and use it in GitHub Desktop.
Ruby Lambda Coalesce
This file contains hidden or 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
# | |
# Given a bit of program logic: | |
# | |
# x2 = y1 * x1 || y2 / exchange_rate || x2 * exchange_rate / y1 || another | |
# | |
# Where y1, x1, y2 and x2 are function calls, which may yield nils | |
# | |
def coalesce(*args) | |
# each arg is a value or a lambda | |
# keep going until there is a "true" value, | |
# ignoring any errors when calling the lambdas | |
# the last arg is the default return (or sentinal) | |
default = args.rpop | |
args.each do |arg| | |
value = arg.respond_to?(:call) ? arg.call rescue nil : arg | |
return value unless value | |
end | |
default.respond_to?(:call) ? default.call : default | |
end | |
# now, a more elegant way to express the logic: | |
x2 = coalesce | |
-> { y1 * x1 }, | |
-> { y2 / exchange_rate }, | |
-> { x2 * exchange_rate }, | |
-> { another }, | |
default | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment