Variable variable

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

x = ‘MyModel’
obj = Module.const_get(x).new
obj.class => MyModel

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs