Forum: Ruby on Rails dynamic variable names?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
railsonly (Guest)
on 2005-11-27 22:06
(Received via mailing list)
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
james.adam (Guest)
on 2005-11-28 00:00
(Received via mailing list)
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
craig (Guest)
on 2005-11-28 00:12
(Received via mailing list)
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: removed_email_address@domain.invalid
Xeriom.NET    | f: +44 (0)709 287 1902 | w: http://xeriom.net
david.felstead (Guest)
on 2005-11-28 01:16
(Received via mailing list)
Hi Frank,

You could do:

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

or, for instance variables:

self.instance_variable_set(:@var_name, value)

Cheers!

-DF
railsonly (Guest)
on 2005-11-28 19:23
(Received via mailing list)
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.
railsonly (Guest)
on 2005-11-28 19:23
(Received via mailing list)
Hi David,
Thanks, I'll try that out.
-Frank
This topic is locked and can not be replied to.