From: Andrew Cowan Date: 2001-10-20T05:46:24+09:00 Subject: [ruby-talk:22799] Re: Creating variables with dynamic names ? Avi Bryant wrote: > On Sat, 20 Oct 2001, Julian Fitzell wrote: > >> var_name = "myVar" >> eval "#{var_name} = 10" >> myVar => 10 > > Although that will work in IRB, it won't work in general, because > eval creates a new scope. So this would work: > > myVar = 1 > var_name = "myVar" > eval "#{var_name} = 10" > myVar => 10 > > but if myVar isn't already defined it will only last for the scope of the > eval. > > I can't think of any good way of getting that effect, but I will say that > in most cases, I would expect there to be a better way to solve the > problem. > > On the other hand, if you're using instance variables instead of locals, > it should work fine: > > var_name = "@myVar" > eval "#{var_name} = 10" > @myVar => 10 > > Globals ought to work too. > > Avi > >> On 20/10/2001 at 1:25 AM Andrew Cowan wrote: >> >> >I am somewhat new to Ruby, coming from about 10 years of Perl >> >programming, >> >6 professionally. >> > >> >In perl, it is easy to create new variables with variable names that are >> >defined in another variable. For example: >> > >> >$var_name = "myVar"; >> >${"$var_name"} = 10; >> > >> >would define a new variable $myVar the value 10. >> > >> >Is there a way to do this in Ruby? I suspect there must be but haven't >> >been >> >able to figure this out yet. >> > >> >Thanks for any help you can offer! >> > >> >Andy >> > >> >______________________________________________________________________ >> >Posted Via Uncensored-News.Com - Still Only $9.95 - >> >http://www.uncensored-news.com >> > With NINE Servers In California And Texas - The Worlds Uncensored >> > News Source >> >> >> >> > > > Was just going to post that indeed it does work, and then I realized I was using instance variables. ;) Thanks for the followup! ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With NINE Servers In California And Texas - The Worlds Uncensored News Source