On Sat, 23 Dec 2000, David Alan Black wrote:

> > But I would use the #{} construct in strings ...
> > 
> >   for letter in 'a' .. 'z'
> >     eval "%{letter} = Planet.new"
> >     eval "%{letter}.name('%{letter}')"
> >   end
> 
> (s/%/#/g)
> 
> The only thing is, each of those variables (a..z) goes out of scope
> when its iteration of the block ends.  So you'd either have to declare
> them first (which you'd have to do one-by-one, unless there's a way to
> declare them in a loop, in which case my whole point is moot because
> you could just use that technique in the original loop...) -- or
> possibly use a hash to store the objects:

"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'
  irb> b
  NameError: undefined local variable or method `b' for #<Object:0x40181ce0>
  (irb):5:in `irb_binding'
  irb> c
  NameError: undefined local variable or method `c' for #<Object:0x40181ce0>
  (irb):6: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"
  irb> b
  "This variable is b"
  irb> c
  "This variable is c"

So the given code (with # instead of %) works fine.

-- 
  steve / deaf.org