Ruby String # to_class

Tirado de umanterior postar com algumas modificações para respondersepp2kComente sobre namespaces, eu tenho implementado o método String # to_class. Eu estou compartilhando o código aqui e eu acredito que poderia ser refatorado de alguma forma especialmente o contador "i". Seus comentários são bem-vindos.

 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

questionAnswers(3)

yourAnswerToTheQuestion