And is there any other way to create variables in a dynamical manner,
using something else than eval(), or can only the parser create
variables?
Greetings,
Geert.

-----Original Message-----
From: Robert Klemme [mailto:bob.news / gmx.net] 
Sent: 30 May 2005 14:55
To: ruby-talk ML
Subject: Re: creating variable with eval


This comes up again and again.  You might want to search the archives.

Short story: Ruby determines local variables at parse time.  Although
you
can bind values to local vars with eval you cannot access them outside
of
eval because they are not known there:

14:44:40 [source]: ruby -e 'eval("x=10");p(eval("x"))'
10
14:44:46 [source]: ruby -e 'eval("x=10");p x'
-e:1: undefined local variable or method `x' for main:Object (NameError)
14:44:51 [source]: ruby -e 'x=nil;p x;eval("x=10");p x'
nil
10

Apart from that: your dynamic created variables will be of no use as the
method body cannot access them.  The simplest solutions:

 1) Access the hash instead of using local vars

 2) Generate the complete method code

In any case: make sure you have default values so you can init variables
not defined in the hash.  Otherwise you'll see the same error:

14:48:05 [source]: ruby -e 'def x(a) b + a end;x 10'
-e:1:in `x': undefined local variable or method `b' for main:Object
(NameError)
        from -e:1

Kind regards

    robert