It's possible to call a lambda from another lambda:
first = -> { 'Ok' }
second = -> { first.call }
puts second.call
# => 'Ok'
but when the order is reversed:
first = -> { second.call }
second = -> { 'Ok' }
puts first.call
the code fails with a NameError
:
lambda_order.rb:1:in `block in <main>': undefined local variable or method `second' for main:Object (NameError)
Did you mean? send
from lambda_order.rb:3:in `<main>'
even though :second
seems to be a local variable inside the scope of first
:
first = -> { local_variables }
second = -> { 'Ok' }
p first.call
# => [:first, :second]
I only use lambdas for golfing purposes so I'm not sure what's going on with the scope. Replacing second
by a method or a constant lambda fixes the NameError
. It seems related to this question but in my case, both lambdas are defined in main
.
Could you please explain?