"Peter Hickman" <peter / semantico.com> schrieb im Newsbeitrag news:41EBA48B.1030901 / semantico.com... > Luc Heinrich wrote: > > >Peter Hickman <peter / semantico.com> wrote: > > > > > > > >> return klass.new(data) > >> > >> > > > >return Kernel.const_get(klass).new(data) > > > >Note that const_get will throw an exception if the passed class name is > >unknown, so be prepared to deal with that. > > > > > > > Actually, trying to catch the error seems to be harder than it should > be. For example: > > class Builder > def Builder.create( klass_sym, data ) > begin > return Kernel.const_get( klass_sym ).new( data ) > rescue > raise "There was an error" > end > end > end > > Should report "There was an error" when const_get fails. However this is > untrapped. > > xx.rb:26:in `const_get': uninitialized constant Bernie at Kernel (NameError) > from xx.rb:26:in `create' > from xx.rb:43 > > I've tried splitting this up into individual steps: > > x = Kernel.const_get( klass_sym ) > x.new( data ) > > but this makes no difference. You need to catch NameError. class Builder def Builder.create( klass_sym, data ) begin return Kernel.const_get( klass_sym ).new( data ) rescue NameError => e raise "There was an error: #{e}" end end end robert