On Fri 27 Sep 2002 at 08:51:05 +0900, Alan Chen wrote:

> On Fri, Sep 27, 2002 at 08:38:22AM +0900, Travis Whitton wrote:
> > 
> > Iterators don't introduce a new scope for previously defined variables.  It's
> > in the documentation but anybody who's just learning "on the fly" will
> > certainly find this surprising. It's my least favorite feature about Ruby
> > because while everything else feels right, it feels dead wrong(coming from
> > Perl's lexical scoping rules).
> 
> I must be missing something here, in perl I can do this:
> 
> $sum = 0;
> for (0..10) { sum += $_; }
> # sum => 56
> 
> sum = 0
> 0.upto(10) { |i| sum += i }
> # sum => 56
> 
> 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 access the outer scope unless you explicitly request a
locally scoped variable of the same name, using 'my'.

What Travis is saying feels wrong to him is that the Ruby behaviour is
not uniform: you access and change the value of the variable in the
outer scope if a variable with the same name has already been defined,
but you create a locally scoped variable if the outer scope contains
no such variable.

I have to say that this still feels odd to me after nine months of
Ruby coding. Once you know about it, you can take it into account, but
anyone not learning the language from a book is likely to get caught
out by this.

Ian
-- 
Ian Macdonald               | Ha.  For once you're both wrong but not
ian / caliban.org             | where you are thinking.   - Larry McVoy to 
                            | Linus Torvalds on linux-kernel 
                            | 
                            |