From: ara.t.howard@... Date: 2006-01-20T06:12:22+09:00 Subject: Re: Dynamic class instantiation On Fri, 20 Jan 2006, Jason wrote: > Hi all, > > I have a situation where I need to dynamically execute an object from a > String name. I read in pickaxe that as long as a capitalize the class > name in the string, Ruby will see it as a Constant and thusly allow me > to use it. > > For example: > > module Test > > class MyClass > def do_something > puts "Something done." > end > end > > end > > (caller code) > > cls = "Test::MyClass" > require cls > obj = cls.new > obj.do_something > > ------ > > When I execute the above caller code, I get an error saying > > undefined method `new' for "Test::MyClass":String (NoMethodError) > > So, obviously, Ruby is telling me that there is no new method for the > String "Test::MyClass". I'm trying to instantiate the class this way as > I have specific methods that return object besides String, so I'm > guessing eval(cls) isn't appropriate for me. Also, I checked the > archives on the list with no luck. > > Any suggestions? > > Thx, def klass_stamp(hierachy, *a, &b) ancestors = hierachy.split(%r/::/) parent = Object while((child = ancestors.shift)) klass = parent.const_get child parent = klass end klass::new(*a, &b) end class A; class B;end; end klass_stamp 'A::B' hth. -a -- strong and healthy, who thinks of sickness until it strikes like lightning? preoccupied with the world, who thinks of death, until it arrives like thunder? -- milarepa