[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

ruby1.9 block scope

Daniel DeLorme

9/29/2008 10:55:00 AM

I could have sworn that one of the firm changes in ruby 1.9 was that
variables defined inside a block would also exist outside the block. But
when I try it:

>> 1.times{ x=2 }
=> 1
>> x
NameError: undefined local variable or method `x' for main:Object

Did I dream all that? If it wasn't a dream, when and why was that change
reversed?

Daniel

2 Answers

James Coglan

9/29/2008 10:59:00 AM

0

[Note: parts of this message were removed to make it a legal post.]

>
> I could have sworn that one of the firm changes in ruby 1.9 was that
> variables defined inside a block would also exist outside the block


No, it's the reverse. Take this:

x = 5
1.upto(10) { |i| x = i }
puts x

ruby1.8 prints "10", ruby1.9 should print "5".

Daniel DeLorme

9/29/2008 11:42:00 AM

0

James Coglan wrote:
>> I could have sworn that one of the firm changes in ruby 1.9 was that
>> variables defined inside a block would also exist outside the block
>
>
> No, it's the reverse. Take this:
>
> x = 5
> 1.upto(10) { |i| x = i }
> puts x
>
> ruby1.8 prints "10", ruby1.9 should print "5".

Actually you are confusing things a litte. In this case ruby1.9 prints
"10". Only the block *parameters* are local to the block:
>> i = "a"
=> "a"
>> 2.times{ |i| puts i }
0
1
=> 2
>> puts i
a

Which is nice, but not nearly as nice as having the variables assigned
inside the block available outside of it. These slides are quite old but
this was the original plan:
http://www.rubyist.net/~matz/slides/rc2003/mgp...

And I seem to remember I experienced that behavior in 1.9 a few months
ago only. But not any more :-(

--
Daniel