I prefer to save variables in a hash table.


irb(main):001:0> da=Hash.new
{}
irb(main):002:0> da[ "z" ] = 3
3
irb(main):003:0> da
{"z"=>3}
irb(main):004:0> var_name = "myVar"
"myVar"
irb(main):005:0> da[var_name]=10
10
irb(main):006:0> da
{"myVar"=>10, "z"=>3}
irb(main):007:0>



--- Avi Bryant <avi / beta4.com> 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
>