Local variables in lambda

L

List.rb

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
 
B

Brian Candler

List said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,634
Latest member
RonnyBoelk

Latest Threads

Top