From: Igal Koshevoy Date: 2008-07-02T01:48:16+09:00 Subject: Re: Dynamic Variables Charles Oliver Nutter wrote: > Igal Koshevoy wrote: >> # Python >> counter = 52 >> eval(compile('box%s = "cat and dogs"' % counter, '', 'exec')) >> print box52 # => "cat and dogs" >> >> # Perl >> $counter = 52; >> eval("\$box$counter = 'cat and dogs'"); >> print $box52, "\n"; # => "cat and dogs" > > In python, local variables are not (necessarily) determined at > parse/compile time. They're slots in a local scope that can grow later > on. > > In Ruby, this behavior only exists for eval scopes. Ruby 1.8 shares a > single eval scope under any given normal scope across all evals in > that normal scope. Ruby 1.9 instantiates a new eval scope for each eval. > > I don't know what Perl does. Charles, thanks for the clarification about the scoping behaviors. I suppose if I really want to pretend like I was dynamically injecting a local variable into a local scope, and a class/instance variable didn't weren't desirable, then I could resort to: def set(name, value) self.class.send(:attr_accessor, name) self.send("#{name}=", value) end counter = 52 set "box#{counter}", "cat and dogs" p box52 # => "cat and dogs" -igal