Variable variable

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

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
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

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