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::C::Y::Z', 1, 0, 1, 0, 1, 0){ |n| p n }
harp:~ > ruby a.rb
42
HTH.
-a
···
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.
--
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
On 4/29/05, James Edward Gray II <james@grayproductions.net> wrote:
On Apr 29, 2005, at 12:38 PM, 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.
If your class is nested in a module or other class, you might want to do
something like:
irb:0> module A
irb:1> class B
irb:2> class C
irb:3> end
irb:2> end
irb:1> end
=> nil
irb:0> classname = 'A::C'
=> "A::C"
irb:0> klass = classname.split('::').inject(Class) do |sum, elem|
irb:1* sum.const_get(elem)
irb:1> end
=> A::C
irb:0> klass.new
=> #<A::C:0xb7d12640>
···
On Sat, 2005-04-30 at 03:05 +0900, James Edward Gray II wrote:
On Apr 29, 2005, at 12:38 PM, 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.