Create an object from a string?


#1

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
up
too long – can’t find it. In Java, I’d be doing something like this:

Class.forName(“Car”).newInstance();

Any help greatly appreciated.

John


#2

2006/1/19, John McGrath removed_email_address@domain.invalid:

Class.forName(“Car”).newInstance();

(eval “Time”).new


#3

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
end
end
end

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

Zach


#4

On 1/19/06, John McGrath removed_email_address@domain.invalid wrote:

Class.forName(“Car”).newInstance();
The other examples so far will work, but in Rails you can simply do:
instance = string_containing_class_name.constantize.new

e.g.
class_name = “Motorcycle”
@motorcycle = class_name.constantize.new

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


#5

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