Undefined local variable?

Z

Zhi-Qiang Lei

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
(e-mail address removed)
 
B

Brian Candler

Yukihiro Matsumoto wrote in post #970434:
Hi,

In message "Re: Undefined local variable?"
on Fri, 24 Dec 2010 14:48:41 +0900, Zhi-Qiang Lei

|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.
 

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
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top