Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   Strange behaviour regarding lexical scopes? (http://www.velocityreviews.com/forums/t816377-strange-behaviour-regarding-lexical-scopes.html)

Michal 08-27-2004 09:59 AM

Strange behaviour regarding lexical scopes?
 
Hello,

today (when explaining bits of Ruby to my friend)
I got confused by this:

$ cat a.rb
b = 4
if b == 1
a = 1
end
p a

$ ./a.rb
nil

$ ruby --version
ruby 1.8.2 (2004-07-29) [i686-linux]

(latest gentoo ebuild)

Why is it that 'a' is nil and not undefined? (i would expect:

undefined local variable or method `a' for main:Object (NameError)

)

Thanks in advance,
M.
--
# Michal Safranek, email:
a=(("a".."z").to_a+["@","."]);p(("%b"%[0x645bbb83a6a496]
).scan(/...../).map{|x|a[Integer("0b"+x)]}.join.reverse)



Robert Klemme 08-27-2004 10:39 AM

Re: Strange behaviour regarding lexical scopes?
 

"Michal" <lists+rubytalk@box.cz> schrieb im Newsbeitrag
news:20040827095945.GB26572@box.cz...
> Hello,
>
> today (when explaining bits of Ruby to my friend)
> I got confused by this:
>
> $ cat a.rb
> b = 4
> if b == 1
> a = 1
> end
> p a
>
> $ ./a.rb
> nil
>
> $ ruby --version
> ruby 1.8.2 (2004-07-29) [i686-linux]
>
> (latest gentoo ebuild)
>
> Why is it that 'a' is nil and not undefined? (i would expect:
>
> undefined local variable or method `a' for main:Object (NameError)
>
> )
>
> Thanks in advance,
> M.


"if" doesn't introduce a new scope, similar to "switch" in C et. al. So "a"
and "b" reside really in the same scope and the definition in the true
clause is sufficient to make "a" defined. The assignment need not be
executed.

Kind regards

robert



All times are GMT. The time now is 07:30 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.