From: Travis Whitton Date: 2002-09-28T00:02:39+09:00 Subject: Re: Ruby - common pitfalls? > I understand the value of local scoping in the blocks, but if I wanted > to access variables with external scope, how would you go about doing > that? In Perl you have a choice: # External scope $sum = 0; for (0..10) { $sum += $_; } print "$sum\n"; # Use a new scope $sum = 0; for (0..10) { my $sum += $_; } print "$sum\n"; From perldoc: The "my" keyword declares the listed variable to be local (lexically) to the enclosing block, file, or "eval". The surprising thing about the Ruby version is that it only creates a locally scoped variable if an external variable of the same name doesn't exist. It would be more natural if the block introduced a local variable to the block by default and there was some other facility to use the external variable. I don't think matz wants to break backward compatibility, so I doubt this will change. There are some interesting comments on rubygarden.org regarding this problem, and I like the suggestion of using <> to locally scope a variable. a = 0 1.upto(3) do # some code end # a is now 0 However, judging by this poll http://www.rubygarden.org/pollBooth.php?op=results&pollID=13 it looks like most people would like the default behaviour to be that variables inside of || to be local. - Travis Whitton