vooD
vooD

Reputation: 2921

Reflection in Ruby. Instantiate an object by given class name

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

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

Upvotes: 25

Views: 11250

Answers (3)

Randy Simon
Randy Simon

Reputation: 3324

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

array_object = "Array".constantize.new

Upvotes: 24

Geo
Geo

Reputation: 96997

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

Upvotes: 6

John Topley
John Topley

Reputation: 115432

You can do this:

arrayObject = Object::const_get('Array').new

Upvotes: 33

Related Questions