Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #2920

Re: scope of assignments with lambda

From Kevin Mahler <kevin.mahler@yahoo.com>
Newsgroups comp.lang.ruby
Subject Re: scope of assignments with lambda
Date 2011-04-15 01:37 -0500
Organization Service de news de lacave.net
Message-ID <90f821efcacb67d7fe0de170d6979e29@ruby-forum.com> (permalink)
References <5ab8b94d707235d7b83c9b011b696ef4@ruby-forum.com> <2b8e0c638f80e0062cbba1f68ca297d8@ruby-forum.com> <470a9e96982d7a927f140193f12c0f64@ruby-forum.com>

Show all headers | View raw


Fearless Fool wrote in post #988777:
> What I was surprised about was the scoping of variables in assignment
> statements.  I guess it makes sense.  Assume that p is previously
> undefined, then a reference on the RHS to p like this:
>
>   p = p + 1
>
> will raise an error.  But wrapped inside a lambda, the reference to p is
> deferred, so it all works:
>
>   p = lambda { |n| p.call(n-1) if (n > 0) }
>
> As I said, that's the power of a lexical closure.

"The scoping of variables in assignment" is exactly the same in both
cases.

p = p + 1 does not fail because p is undefined. p is defined. Its
value is nil. The error results from NilClass#+ not existing. This has
nothing to do with "the power of the lexical closure".

Local variables are discovered at compile time. p gets defined at the
beginning of the scope, *before* the line "p = p + 1", and it's
assigned the value of nil. Try

  p = p.to_i + 1

and observe the non-error. Even better, try

  def foo
    puts local_variables #=>bar
    bar = 99
  end

The reference to p inside the lambda is not deferred. At compile-time,
the p inside the lambda is bound to the local variable p, just as the
p on the right-hand side of "p = p + 1" is bound to the local variable
p. There is nothing special going on as a result of the lambda being
present.

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | Next | Find similar | Unroll thread


Thread

Re: scope of assignments with lambda Kevin Mahler <kevin.mahler@yahoo.com> - 2011-04-15 01:37 -0500

csiph-web