Thursday, April 12, 2007

Ruby Scoping Shocker

Ruby head-scratching magic:


irb(main):001:0> if false
irb(main):002:1> x = true
irb(main):003:1> end
=> nil
irb(main):004:0> x
=> nil
But now:
irb(main):005:0> y
NameError: undefined local variable or method `y' for main:Object
from (irb):5
irb(main):006:0>

This here is very unusual, and I'm not sure if it is part of the Ruby specification or just the implementation. From what I gather, the declaration of 'x' is a side effect of the parsing of the conditional block. What other side effects to unexecuted code are there that we should know about?


The oddity does not carry over to the right side of assignment:


irb(main):001:0> if false
irb(main):002:1> x = y
irb(main):003:1> end
=> nil
irb(main):004:0> x
=> nil
irb(main):005:0> y
NameError: undefined local variable or method `y' for main:Object
from (irb):5
irb(main):006:0>

Why is the specification/implementation question important?


Because if we could rely on this behavior we could write more compact code, writing fewer variable declarations. For example:


if some_condition
x = true
end
#..
do_something if x

rather than:


x = nil
if some_condition
x = true
end
#..
do_something if x

if we can count on this in future and all implementations of Ruby.

2 comments:

Anonymous said...

Good dispatch and this enter helped me alot in my college assignement. Gratefulness you for your information.

Anonymous said...

[url=http://kfarbair.com][img]http://www.kfarbair.com/_images/logo.png[/img][/url]

בית מלון [url=http://www.kfarbair.com]כפר בעיר[/url] - [url=http://www.kfarbair.com/about.html]חדרים[/url] גדולים אנחנו מספקים שירותי אירוח מיוחדים גם ישנו במקום שירות חדרים המכיל [url=http://www.kfarbair.com/eng/index.html]סעודות רומנטיות[/url] במחירים מפתיעים אשר מוגשות ישירות לחדרכם...

לפרטים נוספים נא לפנות לאתר האינטרנט שלנו - [url=http://kfarbair.com]כפר בעיר[/url] [url=http://www.kfarbair.com/contact.html][img]http://www.kfarbair.com/_images/apixel.gif[/img][/url]