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 `<main>'
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 `<main>'
Best regards,
Zhi-Qiang Lei
zhiqiang.lei@gmail.com
Yukihiro Matsumoto wrote in post #970434:
Hi,
>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.
···
In message "Re: Undefined local variable?" > on Fri, 24 Dec 2010 14:48:41 +0900, Zhi-Qiang Lei > <zhiqiang.lei@gmail.com> writes:
--
Posted via http://www.ruby-forum.com/\.