How to convert a string to a constant in Ruby?

Ruby

Ruby Problem Overview


How to convert the string "User" to User?

Ruby Solutions


Solution 1 - Ruby

Object.const_get("User")

No need to require ActiveSupport.

Solution 2 - Ruby

You can use the Module#const_get method. Example:

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

Solution 3 - Ruby

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

"User".constantize

Solution 4 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarshlucaView Question on Stackoverflow
Solution 1 - RubyDamienView Answer on Stackoverflow
Solution 2 - RubyChris Jester-YoungView Answer on Stackoverflow
Solution 3 - RubyseverinView Answer on Stackoverflow
Solution 4 - RubypsyhoView Answer on Stackoverflow