开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜