Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically instantiate a Ruby class similar to Java

Tags:

java

ruby

How can this line in Java be translated to Ruby:
String className = "java.util.Vector";
...
Object o = Class.forName(className).newInstance();

Thanks!


2 Answers

Object::const_get('String').new()
like image 77
Ken Avatar answered Sep 12 '25 22:09

Ken


If you're using ActiveSupport (i.e. Rails), there is a method added to String that does this:

"String".constantize.new
like image 37
Ian Terrell Avatar answered Sep 12 '25 20:09

Ian Terrell