Dynamic object creation

Hi all,

I couldn’t quite find the answer I was looking for on Google (though
it’s probably there somewhere), so I’ll pose the question here.

I have a situation where the class and module names are identical. I
want to dynamically generate an object based on a string.

m = "TestClass"
require "#{m}"
t = eval “#{m}.new”

This works, but I’m wondering if there’s a more “graceful” approach.

Thanks in advance.

Regards,

Dan

m = "TestClass"
require "#{m}"
t = eval "#{m}.new"

eval is evil

pigeon% cat TestClass.rb
class TestClass
end
pigeon%

pigeon% cat b.rb
#!/usr/bin/ruby
m = "TestClass"
require m
p Object.const_get(m).new
pigeon%

pigeon% b.rb
#<TestClass:0x401af914>
pigeon%

Guy Decoux

Hi –

Hi all,

I couldn’t quite find the answer I was looking for on Google (though
it’s probably there somewhere), so I’ll pose the question here.

I have a situation where the class and module names are identical. I
want to dynamically generate an object based on a string.

m = “TestClass”
require “#{m}”
t = eval “#{m}.new”

This works, but I’m wondering if there’s a more “graceful” approach.

#require just wants a string:

irb(main):005:0> d = “parsedate”
“parsedate”
irb(main):006:0> require d
true

To go from string to constant, you can use Module#const_get:

irb(main):007:0> s = “String”
“String”
irb(main):008:0> str = type.const_get(s).new(“hi”)
“hi”

David

···

On Fri, 26 Jul 2002, Daniel Berger wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav