Instantiate a class dynamically

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

Le 24 janvier 2009 à 02:12, [email protected] a écrit :

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

On Jan 23, 5:25 pm, “F. Senault” [email protected] wrote:

my_object = Class(my_string)
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

[email protected][email protected] writes:

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
{}

Hi –

On Sat, 24 Jan 2009, F. Senault wrote:

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.)

I don’t think so:

$ ruby19 -ve ‘p Object.const_get(“String”)’
ruby 1.9.1 (2008-12-30 patchlevel-0 revision 21203)
[i386-darwin9.5.0]
String

David


David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Coming in 2009: The Well-Grounded Rubyist (The Well-Grounded Rubyist)

http://www.wishsight.com => Independent, social wishlist management!

Le 24 janvier à 03:16, James G. a écrit :

On Jan 23, 2009, at 7:28 PM, F. Senault wrote:

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

(The to_sym is mandatory in ruby 1.9.)

Na.

You are, of course, perfectly right. I should do my tests after the
coffee… :slight_smile:

Fred

On Jan 23, 2009, at 7:28 PM, F. Senault wrote:

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. :wink:

James Edward G. II