Forum: Ruby on Rails create an object from a string?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
John McGrath (Guest)
on 2006-01-19 12:27
(Received via mailing list)
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
Lugovoi N. (Guest)
on 2006-01-19 12:33
(Received via mailing list)
2006/1/19, John McGrath <removed_email_address@domain.invalid>:
> Class.forName("Car").newInstance();
>

(eval "Time").new
zdennis (Guest)
on 2006-01-19 12:33
(Received via mailing list)
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
Wilson B. (Guest)
on 2006-01-19 19:30
(Received via mailing list)
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.
Mike P. (Guest)
on 2006-01-19 23:26
(Received via mailing list)
Take a look at YAML. It makes it trivial to make a whole object graph
from a string.
This topic is locked and can not be replied to.