views:

132

answers:

3

I came to ruby from PHP. How could i do the next thing in ruby?

$className = 'ArrayObject';
$arrayObject = new $className();

Thank you for any help!

+4  A: 

You can do this:

arrayObject = Object::const_get('Array').new
John Topley
Cool! Thanks a lot!
vooD
+3  A: 

You can also use the following if you are using Ruby on Rails:

array_object = "Array".constantize.new
Randy Simon
Looks like solution from RoR. Thank you!
vooD
It's worth pointing out that `constantize` is a core extension added to Ruby by the Rails' ActiveSupport module i.e. it's not pure Ruby.
John Topley
Good point John, I've updated my answer.
Randy Simon
+2  A: 

If you have a class, like for example String:

a = String
a.new("Geo")

would give you a string. The same thing applies to other classes ( number & type of parameters will differ of course ).

Geo
While this doesn't directly answer the question, it's a good point that since classes are objects, you can store them just like any other object and this might be a better approach in many cases where you'd be tempted to use a string in another language.
Chuck