25

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

Thanks!

2 Answers 2

47
Object::const_get('String').new()
2
  • 10
    If you'd like to instantiate a class inside a module you just use the module instead of Object. MyCoolModule::Submodule.const_get('MyString').new
    – gaqzi
    May 2, 2009 at 15:30
  • 1
    What if you don't even know the submodule?
    – yas4891
    Apr 13, 2013 at 4:41
26

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

"String".constantize.new

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy