From: Ara.T.Howard@... Date: 2005-04-30T05:04:38+09:00 Subject: Re: Creating arbitrary objects On Sat, 30 Apr 2005, Matthew Thill wrote: > I've probably overlooked something, and hopefully someone can help me > out. I want to be able to create arbitrary object from the contents of a > string. > > For example, if I had the following string: > > classname = "Array" > > How can I create an Array object, knowing only that the variable > classname held the name of some class as a string. this is from my utility lib: harp:~ > cat a.rb 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 module A module B module C class X class Y class Z def initialize(*bits, &block) n = 0 bits.reverse.each_with_index{|bit, i| n |= (bit << i)} block.call n end end end end end end end klass_stamp('A::B::C::X::Y::Z', 1, 0, 1, 0, 1, 0){ |n| p n } harp:~ > ruby a.rb 42 HTH. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | renunciation is not getting rid of the things of this world, but accepting | that they pass away. --aitken roshi ===============================================================================