From: Igal Koshevoy Date: 2008-07-01T21:00:00+09:00 Subject: Re: Dynamic Variables Frederick Cheung wrote: > > On 1 Jul 2008, at 10:52, Igal Koshevoy wrote: > >> irb(main):010:0> counter = 52 >> => 52 >> irb(main):011:0> eval "box#{counter} = 'cat and dogs'" >> => "cat and dogs" >> irb(main):012:0> box52 >> => "cat and dogs" >> > Although that doesn't work outside of irb. (although you can change > the value of an existing local variable like that) > See also > http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/a954f8aaf698a0b9/e1c761b71b63b82e?#e1c761b71b63b82e > > Thanks for catching the mistake and providing the link. So there really is no way to get the "box52" variable directly? It's only available within the context of an eval? When I run the code below directly (not from IRB), the interpreter is clearly seeing the "box52" local variable and keeping its state around, but won't let me access it without wrapping an eval around it, which seems wrong: counter = 52 p local_variables # => ["counter"] eval "box#{counter} = 'cat and dogs'" p local_variables # => ["counter", "box52"] p eval("box52") # => "cat and dogs" p box52 # => undefined local variable or method `box52' for main:Object (NameError) I say "seems wrong" because I'm used to the following behavior: # 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" -igal