Strange behaviour regarding lexical scopes?

M

Michal

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

Robert Klemme

Michal said:
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
 

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
474,434
Messages
2,571,689
Members
48,796
Latest member
Greg L.

Latest Threads

Top