instantiate a class dynamically

R

rpardee

Hey All,

If I have the name of a class in a string var, is it possible to get a
new instance of that class (and if so, how)? The following do *not*
work:

my_string = "Hash"

my_object = Class(my_string)
my_object = Class.new(my_string)
my_object = Object.new(my_string)

Thanks!

-Roy
 
F

F. Senault

Le 24 janvier 2009 à 02:12, (e-mail address removed) a écrit :
Hey All,

If I have the name of a class in a string var, is it possible to get a
new instance of that class (and if so, how)? The following do *not*
work:

my_string = "Hash"

my_object = Class(my_string)
my_object = Class.new(my_string)
my_object = Object.new(my_string)

my_object = Object.const_get(my_string.to_sym).new

(The to_sym is mandatory in ruby 1.9.)

Fred
 
R

rpardee

Le 24 janvier 2009 02:12, (e-mail address removed) a crit :





my_object = Object.const_get(my_string.to_sym).new

(The to_sym is mandatory in ruby 1.9.)

Fred
--
Any time tomorrow a part of me will die
And a new one will be born
Any time tomorrow  I'll get sick of asking why
Sick of all the darkness I have worn            (K's Choice, Shadow Man)

Awesome cool--looks like I can even pass arguments into new() (which
would have been my next question).

Thanks very much!

-Roy
 
P

Pascal J. Bourguignon

Hey All,

If I have the name of a class in a string var, is it possible to get a
new instance of that class (and if so, how)? The following do *not*
work:

my_string = "Hash"

my_object = Class(my_string)
my_object = Class.new(my_string)
my_object = Object.new(my_string)

Class names are used to define constants in the Module module:


irb(main):014:0> className="Hash"
"Hash"
irb(main):015:0> Module.constants.member?(className)
true

Therefore you should be able to get the class with:

irb(main):016:0> Module.class_eval(className)
Hash

and make an instance with:

irb(main):017:0> Module.class_eval(className).new
{}
 
J

James Gray

my_object = Object.const_get(my_string.to_sym).new

(The to_sym is mandatory in ruby 1.9.)

Na.

$ ruby_dev -ve 'p File.const_get("Stat")'
ruby 1.9.1 (2008-12-30 patchlevel-0 revision 21203) [i386-
darwin9.6.0]
File::Stat

Ruby's a pretty smart gal. ;)

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top