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.
4098ef08ed2ee3eabeb0ddf0ec03f783?d=identicon&s=25 railsonly (Guest)
on 2005-11-27 21: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
05d703f649ef1d07e78d7b479fb4c4ac?d=identicon&s=25 james.adam (Guest)
on 2005-11-27 23: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
5cfd7e9223637ea26c81c2cc3e43799e?d=identicon&s=25 craig (Guest)
on 2005-11-27 23:12
(Received via mailing list)
On 27 Nov 2005, at 20:04, Frank Kim 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 Webster | t: +44 (0)131 516 8595 | e: craig@xeriom.net
Xeriom.NET    | f: +44 (0)709 287 1902 | w: http://xeriom.net
6c27f78ab0eee78732ae54e8b8718b84?d=identicon&s=25 david.felstead (Guest)
on 2005-11-28 00: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
4098ef08ed2ee3eabeb0ddf0ec03f783?d=identicon&s=25 railsonly (Guest)
on 2005-11-28 18: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.
4098ef08ed2ee3eabeb0ddf0ec03f783?d=identicon&s=25 railsonly (Guest)
on 2005-11-28 18:23
(Received via mailing list)
Hi David,
Thanks, I'll try that out.
-Frank
This topic is locked and can not be replied to.