Hello --

On Sat, 23 Dec 2000, Clemens Hintze wrote:

> [Tony wrote:]
>
> > #!/usr/bin/python
> >
> > import string, gebplanet
> >
> > for letter in string.lowercase:
> >     exec '%s=gebplanet.planet()' % letter
> >     exec '%s.name(letter)' % letter
> 
> A Python similar solution would looks like:
> 
>   #!/bin/env ruby
> 
>   require "gebplanet"
> 
>   for letter in 'a' .. 'z'
>     eval "%s = Planet.new" % letter
>     eval "%s.name('%s')" % [letter, letter]
>   end
> 
> 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:

   class Planet
     attr_accessor :name
   end

   planets = {}

   ('a' .. 'z') .each do |let|
     plan = planets[eval ":#{let}"] = Planet.new
     plan.name = "#{let}"
   end

   p planets[:m]  # =>  #<Planet:0x40171be0 @name="m">


which (Perl background?) strikes me as a better technique (if it
wouldn't make your [Tony] port too arduous).


David

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