Dynamic variable names?

Hi,
In Ruby is there a way to create variable names that are dynamic? An
example would be I have a loop and I want to name the variables “foo_0”,
“foo_1”, etc. Obviously in this case I don’t want to use an Array.
Thanks,
Frank

I take it there’s a very good reason why you can’t have an array
called ‘foo’, and store your values in foo[0], foo[1] and so on?

  • james

On 27 Nov 2005, at 20:04, Frank K. wrote:

In Ruby is there a way to create variable names that are dynamic?
An example would be I have a loop and I want to name the variables
“foo_0”, “foo_1”, etc. Obviously in this case I don’t want to use
an Array.

It sounds /exactly/ like you want to use an array here… why
wouldn’t you use an array?

Yours,
Craig

Craig W. | t: +44 (0)131 516 8595 | e: [email protected]
Xeriom.NET | f: +44 (0)709 287 1902 | w: http://xeriom.net

Hi Frank,

You could do:

eval("#{variable_name} = #[value}")

or, for instance variables:

self.instance_variable_set(:@var_name, value)

Cheers!

-DF

I’m not using an array because text_field does not understand arrays, to
be
more specific you can’t do a send of a [n] accessor. I am creating a
page
where you can create multiple records and the only way to do this and
have
values still be present on the page if there is an error is to use
variables
like foo_0, foo_1, foo_2, etc.

Hi David,
Thanks, I’ll try that out.
-Frank