>ruby eval_bench.rb user system total real eval: 1.141000 0.000000 1.141000 ( 1.156000) const_get: 0.156000 0.000000 0.156000 ( 0.172000) >cat eval_bench.rb require 'benchmark' class Foo;end some_class = 'Foo' Benchmark.bm(10) do |b| b.report("eval:") { 100000.times {eval("#{some_class}.new")} } b.report("const_get:") { 100000.times{Object.const_get(some_class).new} } end On 5/4/06, Charlie Bowman <charlie / castlebranch.com> wrote: > I understand the ugliness of eval....but why shouldn't we use it? It is > much quicker to write, shorter to read, and easier to use. > > On Fri, 2006-05-05 at 04:19 +0900, Patrick Hurley wrote: > > > On 5/4/06, Patrick Hurley <phurley / gmail.com> wrote: > > > On 5/4/06, Gregory Seidman <gsslist+ruby / anthropohedron.net> wrote: > > > > On Fri, May 05, 2006 at 03:51:39AM +0900, RGR wrote: > > > > } I want to create an object from a class, but the name of that class is > > > > } in a variable, so the form obj=Class.new(args) can't be used. How can it > > > > } be done? Without using eval, because its a bit messy and unelegant. > > > > } > > > > } The equivalent of obj=$variable_with_class_name(args) in php. > > > > > > > > obj = Object::const_get(class_name).new(args) > > > > > > > > } Thanks. > > > > } RGR > > > > --Greg > > > > > > > > > > > > > > > > > > And if args is an array you want to use as individual params: > > > > > > obj = Module.const_get(class_name).new(*args) > > > > > > (note I prefer Module. but both work) > > > pth > > > > > > > Ara is of course correct, so you end up with something like: > > > > klass = var_with_class.to_s.split('::').inject(Module) { |base,klass| > > base.const_get(klass) } > > obj = klass.new(*args) > > > > If this is a common operation in your code, you could add this into > > Module or some other reasonable place. > > > > pth > > > > > > > >