I would, naively hoping to see YARV released Sometime Soon ™, rather
use
, since it probably is / will be easier for YARV to
work
with , as far as optimizations are concerned. It also
makes the intent of the code clearer.
suppose s contains the name of your class
Module.const_get s does not work unless your class is defined on top
level.
In oder to have the same semantics as
eval(s).new
we have to write
m = Module
s.split(%r{::|.}).each do
|name|
m = m.const_get(name)
end
m.new
I suggest to look at ObjectSpace for another alternative, hardly more
efficent though
Robert
–
Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.
suppose s contains the name of your class
Module.const_get s does not work unless your class is defined on top
level.
In oder to have the same semantics as
eval(s).new
we have to write
m = Module
s.split(%r{::|.}).each do
|name|
m = m.const_get(name)
end
m.new
Module.const_get(s).new
suppose s contains the name of your class
|name|
–
Yup, very nice
What I meant though is that eval seems much simpler and cheaper
Let us see
yet your’s is fine, just look at the mess when searching through
ObjectSpace
cat perf.rb; ruby perf.rb
require ‘benchmark’
module One
class Two
class Three
end
end
end
s=“One::Three”
n = 50000
Benchmark.bm do |x|
x.report("eval "){ n.times{ eval(s).new } }
x.report("split ") { n.times{ s.split(/::/).inject(Object) { |p,
c|
p.const_get(c) }.new } }
x.report(“ObjectSpace”){n.times{x=nil;ObjectSpace.each_object(Class){|cls|
x=cls if
cls.to_s == s};x.new } }
end user system total real
eval 0.280000 0.000000 0.280000 ( 0.372346)
split 0.540000 0.000000 0.540000 ( 0.621870)
ObjectSpace 21.920000 0.070000 21.990000 ( 24.452318)
–
Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.
Albert Einstein
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.