Dear All,
Why is there still NameError?
ruby-1.9.2-p0 > l = ->{ h }
=> #<Proc:0x000001009d7eb0@(irb):1 (lambda)>
ruby-1.9.2-p0 > l.call
NameError: undefined local variable or method h' for main:Object from (irb):1:in
block in irb_binding’
from (irb):2:in call' from (irb):2 from /Users/siegfried/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in
’
ruby-1.9.2-p0 > h = 1
=> 1
ruby-1.9.2-p0 > l.call
NameError: undefined local variable or method h' for main:Object from (irb):1:in
block in irb_binding’
from (irb):4:in call' from (irb):4 from /Users/siegfried/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in
’
Best regards,
Zhi-Qiang L.
[email protected]
Hi,
In message “Re: Undefined local variable?”
on Fri, 24 Dec 2010 14:29:36 +0900, Zhi-Qiang L.
[email protected] writes:
|Why is there still NameError?
Because name resolution for local variables are done in compile time.
matz.
Hi Matz,
Can I refresh it?
On Dec 24, 2010, at 1:45 PM, Yukihiro M. wrote:
Best regards,
Zhi-Qiang L.
[email protected]
Hi,
In message “Re: Undefined local variable?”
on Fri, 24 Dec 2010 14:48:41 +0900, Zhi-Qiang L.
[email protected] writes:
|Can I refresh it?
Basically, no.
matz.
Yukihiro M. wrote in post #970434:
Hi,
In message “Re: Undefined local variable?”
on Fri, 24 Dec 2010 14:48:41 +0900, Zhi-Qiang L.
[email protected] writes:
|Can I refresh it?
Basically, no.
matz.
That’s true; if h wasn’t a local variable at the time the proc was
defined, then it is compiled as a method call.
But as an aside, you can change the value of h if it was a local
variable at the time, even if it is no longer in scope.
ruby-1.9.2-p0 > def foo
ruby-1.9.2-p0 ?> h = 4
ruby-1.9.2-p0 ?> ->{ h }
ruby-1.9.2-p0 ?> end
=> nil
ruby-1.9.2-p0 > l = foo
=> #<Proc:0x00000002229500@(irb):8 (lambda)>
ruby-1.9.2-p0 > l.call
=> 4
ruby-1.9.2-p0 > eval “h=5”, l.binding
=> 5
ruby-1.9.2-p0 > l.call
=> 5
So maybe your solution is to do “h = nil” before defining the proc.