How to convert a string to a constant in Ruby?

How to convert the string "User" to User?


Solution 1:

Object.const_get("User")

No need to require ActiveSupport.

Solution 2:

You can use the Module#const_get method. Example:

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

Solution 3:

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

"User".constantize