# Variable variable

**URL:** <https://www.ruby-forum.com/t/variable-variable/87139>\
**Category:** Rails\
**Created:** [February 28, 2007, 1:40pm UTC](https://www.ruby-forum.com/t/variable-variable/87139 "2007-02-28T13:40:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![newbee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/5f8ce5/32.png) [@newbee](https://www.ruby-forum.com/u/newbee)\
**Post date:** [February 28, 2007, 1:40pm UTC](https://www.ruby-forum.com/t/variable-variable/87139/1 "2007-02-28T13:40:52Z")

</div>

Hi, i also program in php and one of the concepts i miss in ruby is the  
“variable variable”

$a=“test”  
$$a=“test2”

echo $test will output “test2”

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

$objecttocreate=“car”

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

is this possible in ruby?  
i can’t figure it out

---

<div class="post-metadata">

**Author:** ![newbee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/5f8ce5/32.png) [@newbee](https://www.ruby-forum.com/u/newbee)\
**Post date:** [February 28, 2007, 2:26pm UTC](https://www.ruby-forum.com/t/variable-variable/87139/2 "2007-02-28T14:26:27Z")

</div>

x = ‘MyModel’  
obj = Module.const\_get(x).new  
obj.class =\> MyModel

---

<div class="post-metadata">

**Author:** ![newbee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/5f8ce5/32.png) [@newbee](https://www.ruby-forum.com/u/newbee)\
**Post date:** [March 1, 2007, 6:01pm UTC](https://www.ruby-forum.com/t/variable-variable/87139/3 "2007-03-01T18:01:00Z")

</div>

I’m new to Ruby and Rails, too. Chris’ example is very cool - I hadn’t  
seen  
“Module.const\_get” before. A less sophisticated (and much more  
dangerous)  
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.

Jim
