71

How to convert the string "User" to User?

2
  • Are you trying to call a variable function? Commented Mar 2, 2010 at 6:55
  • 1
    I would also like an answer to this question; however, are you trying to create a new constant based on a string, OR find an already initialized constant? Also are you looking for vanilla ruby or also Rails? Commented Aug 26, 2015 at 20:37

4 Answers 4

108
Object.const_get("User") 

No need to require ActiveSupport.

Sign up to request clarification or add additional context in comments.

1 Comment

Usage example: class User; def self.lookup; const_get('SomeClassName);end; end User.lookup will return class itself.
61

You can use the Module#const_get method. Example:

irb(main):001:0> ARGV => [] irb(main):002:0> Kernel.const_get "ARGV" => [] 

Comments

38

If you have ActiveSupport loaded (e.g. in Rails) you can use

"User".constantize 

Comments

30

The recommended way is to use ActiveSupport's constantize:

'User'.constantize 

You can also use Kernel's const_get, but in Ruby < 2.0, it does not support namespaced constants, so something like this:

Kernel.const_get('Foobar::User') 

will fail in Ruby < 2.0. So if you want a generic solution, you'd be wise to use the ActiveSupport approach:

def my_constantize(class_name) unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ class_name raise NameError, "#{class_name.inspect} is not a valid constant name!" end Object.module_eval("::#{$1}", __FILE__, __LINE__) end 

3 Comments

Since Ruby 2.0 has reached EOL, there is no longer any need to pull in ActiveSupport as a dependency to reference a constant with a string. :-)
See also 'User'.safe_constantize
Recommended by whom?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.