Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active November 14, 2018 20:21
Show Gist options
  • Save virtualstaticvoid/519e564c4ce653ec4817 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/519e564c4ce653ec4817 to your computer and use it in GitHub Desktop.
Ruby Lambda Coalesce
#
# 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