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 =开发者_StackOverflow 'ArrayObject';
$arrayObject = new $className();
You can do this:
arrayObject = Object::const_get('Array').new
You can also use the following if you are using Ruby on Rails:
array_object = "Array".constantize.new
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 ).
精彩评论