Dave
Dave

Reputation:

Dynamically instantiate a Ruby class similar to Java

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

Thanks!

Upvotes: 25

Views: 8623

Answers (2)

Ian Terrell
Ian Terrell

Reputation: 10866

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

"String".constantize.new

Upvotes: 26

Ken
Ken

Reputation: 2092

Object::const_get('String').new()

Upvotes: 47

Related Questions