Forum: Ruby Local variables in lambda

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
List R. (Guest)
on 2008-10-29 14:25
(Received via mailing list)
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
Brian C. (Guest)
on 2008-10-29 14:37
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.
This topic is locked and can not be replied to.