Forum: Ruby Undefined local variable?

Posted by Zhi-Qiang Lei (Guest)
on 2010-12-24 06:30
(Received via mailing list)
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
Posted by Yukihiro Matsumoto (Guest)
on 2010-12-24 06:46
(Received via mailing list)
Hi,

In message "Re: Undefined local variable?"
    on Fri, 24 Dec 2010 14:29:36 +0900, Zhi-Qiang Lei 
<zhiqiang.lei@gmail.com> writes:

|Why is there still NameError?

Because name resolution for local variables are done in compile time.

              matz.
Posted by Zhi-Qiang Lei (Guest)
on 2010-12-24 06:49
(Received via mailing list)
Hi Matz,

Can I refresh it?

On Dec 24, 2010, at 1:45 PM, Yukihiro Matsumoto wrote:

>
Best regards,
Zhi-Qiang Lei
zhiqiang.lei@gmail.com
Posted by Yukihiro Matsumoto (Guest)
on 2010-12-24 07:04
(Received via mailing list)
Hi,

In message "Re: Undefined local variable?"
    on Fri, 24 Dec 2010 14:48:41 +0900, Zhi-Qiang Lei 
<zhiqiang.lei@gmail.com> writes:

|Can I refresh it?

Basically, no.

              matz.
Posted by Brian Candler (candlerb)
on 2010-12-24 17:03
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
> <zhiqiang.lei@gmail.com> 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.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.