KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
How do I turn a string into a class name, but only if that class already exists? If Amber is already a class, I can get from a string to the class via: Object.const_get("Amber") or (in Rails) "Amber".constantize But either of these will fail with NameError: uninitialized constant Amber if Amber is not already a class. My first thought is to use the defined? method, but it doesn't discriminate between classes that already exist and those that don't: >> defined?("Object".constantize) => "method" >> defined?("AClassNameThatCouldNotPossiblyExist".constantize) => "method" So how do I test if a string names a class before I try to convert it? (Okay, how about a begin / rescue block to catch NameError errors? Too ugly? I agree...)
Tags (comma-separated)
Save Edits
Cancel