Re: Dynamic class instantiation



unknown wrote:
>
> 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

Actually, I just found this, which is a little simpler, but looks like
it does the same :)

mod = Module
name.split(/::/).each {|m| mod = mod.const_get(m) }
m = mod.new

# Call my method
m.do_something

Thx,

- jason

--
Posted via http://www.ruby-forum.com/.


.



Relevant Pages