From: James Britt Date: 2006-06-08T12:19:14+09:00 Subject: Re: Using a string to find a class Dave Burt wrote: > Pat Maddox wrote: > >> I've got a string, and I want to find out if there's a class with that >> name. So something like >> >> class_exists? "Foo" >> >> and then I can eval it if it does, I guess. Or is there a better way >> than eval in that case? At any rate, I just want to be able to take a >> string and find out if there's a class with that name or not. > > > module.const_get "Foo" > # or just > const_get "Foo" You'll get an exception if Foo isn't defined. And not every constant refers to a class you can instantiate: class Bar ; end kls = Object.const_get "Bar" c = kls.new() # OK Foo = 12 kls = Object.const_get "Foo" c = kls.new() # Not so OK Quick version: def class_exists? kls begin kls = Object.const_get kls kls.kind_of? Class rescue Exception false end end def new_if_class kls, default = nil class_exists?( kls ) ? Object.const_get( kls ).new : default end b = new_if_class "Bar" p b c = new_if_class "Foo" p c -- James Britt "Take eloquence and wring its neck." - Paul Verlaine