# Local variables in lambda

**URL:** <https://www.ruby-forum.com/t/local-variables-in-lambda/152043>\
**Category:** Ruby\
**Created:** [October 29, 2008, 1:25pm UTC](https://www.ruby-forum.com/t/local-variables-in-lambda/152043 "2008-10-29T13:25:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lstrecv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lstrecv](https://www.ruby-forum.com/u/lstrecv)\
**Post date:** [October 29, 2008, 1:25pm UTC](https://www.ruby-forum.com/t/local-variables-in-lambda/152043/1 "2008-10-29T13:25:56Z")

</div>

Hi. Is there a way to create a lambda that references local variables  
not yet defined ( with out pawing them to the prod) ?

I.e.  
x = lambda {a+b}  
a = 1  
b = 2  
c = x.call

Thank you

---

<div class="post-metadata">

**Author:** ![lstrecv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lstrecv](https://www.ruby-forum.com/u/lstrecv)\
**Post date:** [October 29, 2008, 1:37pm UTC](https://www.ruby-forum.com/t/local-variables-in-lambda/152043/2 "2008-10-29T13:37:15Z")

</div>

List Rb wrote:

> Hi. Is there a way to create a lambda that references local variables  
> not yet defined ( with out pawing them to the prod) ?
> 
> I.e.  
> x = lambda {a+b}  
> a = 1  
> b = 2  
> c = x.call

I don’t know what “pawing them to the prod” means, but you can do

a, b = nil, nil  
x = lambda {a+b}  
a = 1  
b = 2  
c = x.call

This is because Ruby makes a parse-time decision as to whether ‘a’ is a  
local variable or a method call. If no assignment to ‘a’ has been seen  
earlier in the scope, then it is interpreted as a method call instead:  
self.a()

Since this is done while the parse tree is built, prior to execution, it  
doesn’t make any difference whether the assignment is actually executed  
or not. For example:

def x  
“hello”  
end

if false  
x = 1  
end

puts x # shows ‘nil’ since x is a local variable

This is necessary to have any sort of efficiency. Otherwise, a simple  
statement like “b = a + 1” inside a loop would have to decide at  
run-time, every time it is executed, whether ‘a’ is a local variable or  
a method.
