From: Calamitas Date: 2008-07-01T19:12:01+09:00 Subject: Re: Dynamic Variables On Tue, Jul 1, 2008 at 11:52 AM, Igal Koshevoy wrote: > Marc Heiler wrote: >> >> Is there any way in ruby to create dynamic variables? >> >> counter = 52 >> box#{counter} = "cat and dogs" >> >> There would be then a new variable >> box52 >> >> Note that this is not a question whether someone should do it or not - >> this is solely whether it is doable or not. Until today I thought it is >> somehow possible with eval but I failed, so I assume it is not possible. >> > > 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" Now try the same thing in plain ruby without irb. Never trust irb on things like these. Dynamic variables as created by eval live in a separate, eval-specific scope and can only be accessed through eval. This is a consequence of Ruby deciding at "compile" time what's a local variable and what's not. So, if you have code like this: eval "a = 5" p a then in "p a", a is determined to be a method call before that code is even run. The a is accessible through eval though: eval "a = 5" p eval("a") Peter