Forum: Ruby on Rails variable variable

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
F7dfce8cd950a0a5cf794bf16e43da6a?d=identicon&s=25 newbee (Guest)
on 2007-02-28 13:40
Hi, i also program in php and one of the concepts i miss in ruby is the
"variable variable"


echo $test will output "test2"

this can be usefull when a field on a form determines which object to


$obj=new $$objecttocreate will create a new car object

is this possible in ruby?
i can't figure it out
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (au5lander)
on 2007-02-28 14:26
(Received via mailing list)
x = 'MyModel'
obj = Module.const_get(x).new
obj.class => MyModel
6ebedec9056fcd5ecff378068cf03f83?d=identicon&s=25 Jimtron (Guest)
on 2007-03-01 18:01
(Received via mailing list)
I'm new to Ruby and Rails, too. Chris' example is very cool - I hadn't
"Module.const_get" before. A less sophisticated (and much more
way to do the same thing would be to use eval:

x = "Foo"
obj = eval("#{x}.new")
obj.class => Foo

Actually, good Rubyists can manage to construct whole classes (and
modules and definitions)
on the fly, not just objects. Cool stuff.

This topic is locked and can not be replied to.