Create an object from a string?

I’m trying to dynamically create an instance of an object at runtime,
from a
String. I have a method that returns one of a number of Strings (“Car”,
“Motorcycle”, “Bicycle”), and when I receive the String, I then want to
instantiate one of those objects.

Seems like there should be a way to do it in Ruby, but maybe I’ve been
too long – can’t find it. In Java, I’d be doing something like this:


Any help greatly appreciated.


2006/1/19, John McGrath [email protected]:


(eval “Time”).new

John McGrath wrote:

Any help greatly appreciated.

If you’re classes are in the top level namespace, you can do…
Object.const_get( ‘Car’ ).new

If you’re classes are in another namespace and you know that namespace,
you can do the same.

module A
module B
class C

c = A::B.const_get( ‘C’ ).new


On 1/19/06, John McGrath [email protected] wrote:

The other examples so far will work, but in Rails you can simply do:
instance =

class_name = “Motorcycle”
@motorcycle =

…and now, @motorcycle is an instance of Motorcycle.

Take a look at YAML. It makes it trivial to make a whole object graph
from a string.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs