Extrait d'un post previous avec quelques modifications pour répondre au commentaire de sepp2k sur les espaces de noms, j'ai implémenté la méthode String # to_class. Je partage le code ici et je crois qu'il pourrait être refacturé d'une manière ou d'une autre en particulier le compteur "i". Vos commentaires sont appréciés.Ruby String # to_class
class String
def to_class
chain = self.split "::"
i=0
res = chain.inject(Module) do |ans,obj|
break if ans.nil?
i+=1
klass = ans.const_get(obj)
# Make sure the current obj is a valid class
# Or it's a module but not the last element,
# as the last element should be a class
klass.is_a?(Class) || (klass.is_a?(Module) and i != chain.length) ? klass : nil
end
rescue NameError
nil
end
end
#Tests that should be passed.
assert_equal(Fixnum,"Fixnum".to_class)
assert_equal(M::C,"M::C".to_class)
assert_nil "Math".to_class
assert_nil "Math::PI".to_class
assert_nil "Something".to_class
Bon travail! J'utiliserais plutôt Benchmark.bmbm pour me réchauffer. Merci! – khelll