On Sat, 23 Dec 2000, Stephen White wrote:

> "for" doesn't have a scope, unlike each {}. Hence any variables defined
> inside a for loop will be accessible.
> 
> Eg:
> 
>   irb> ('a'..'z').each {|i| eval "#{i} = 'This variable is #{i}'" }
>   "a".."z"
>   irb> a
>   NameError: undefined local variable or method `a' for #<Object:0x40181ce0>
>   (irb):4:in `irb_binding'
...
> compared to:
> 
>   irb> for i in ('a'..'z'); eval "#{i} = 'This variable is #{i}'"; end
>   "a".."z"
>   irb> a
>   "This variable is a"
...
> So the given code (with # instead of %) works fine.

Black: Things are not so black and white, White....

Look at what the interpreter does with that (as opposed to irb):

   candle:~/hacking/ruby$ ruby -w
   for i in ('a'..'z'); eval "#{i} = 'This variable is #{i}'"; end
   p e

=> -:2: undefined local variable or method `e'
        for #<Object:0x4017fc90> (NameError)

This has something to do (notice vagueness of explanation) with eval,
rather than for.  If you put a non-evaled assignment in that loop, it
will stick.

It does seem like there should be a way to assign loop-wise to
variables in the scope containing the loop, though....


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav