From: Stefano Crocco Date: 2008-03-08T01:48:19+09:00 Subject: Re: Dynamic class thingies? (Okay, not sure how to title this one) Alle Friday 07 March 2008, coigner ha scritto: > On Fri, 07 Mar 2008 10:11:43 -0500, Stefano Crocco wrote: > > Alle Friday 07 March 2008, coigner ha scritto: > >> Asking for ideas here but let me preface... > > > > > You want Kernel.const_get. As the name suggests, it takes a string and > > returns the value of the constant with that name. For instance: > > > > class C > > end > > > > Kernel.const_get('C').new > > => # > > > > If your classes are defined top-level, that's all you need. If they're > > defined inside a module, you need to call const_get for that module: > > > > module M > > class C > > end > > end > > > > M.const_get('C').new > > > > I hope this helps > > Does and thanks. Though I'd already started getting it to work with eval. > Which do you think is better? Or does it matter? I'd use const_get because it's a tool made for exactly this task, while eval is a much broader tool. Besides, const_get seems also faster: require 'benchmark' Benchmark.bm("const_get".size) do |b| b.report("const_get"){1_000_000.times{Kernel.const_get('C')}} b.report("eval"){1_000_000.times{eval('C')}} end user system total real const_get 0.890000 0.040000 0.930000 ( 0.932886) eval 3.080000 0.100000 3.180000 ( 3.177851) Of course, if you have a deeply nested module hyerarchy, eval might be easier to use. Given this hyerarchy: module A module B module C module D class E end end end end end to get the class E, you'd need the string "A::B::C::D::E". You can obtain E using const_get with this code: "A::B::C::D::E".split('::').inject(Kernel){|res, i| res.const_get i} while using eval you can achieve the same with much less code: eval "A::B::C::D::E" In this case, eval is also faster: require 'benchmark' Benchmark.bm("const_get".size) do |b| b.report('const_get'){1_000_000.times{"A::B::C::D::E".split('::').inject( Kernel){|res, i| res.const_get i}}} b.report('eval'){1_000_000.times{eval "A::B::C::D::E"}} end user system total real const_get 15.360000 0.940000 16.300000 ( 16.299995) eval 5.270000 0.130000 5.400000 ( 5.394793) Stefano