How to convert a string to a constant in Ruby?

前端 未结 5 351
有刺的猬
有刺的猬 2020-11-30 02:36

How to convert the string \"User\" to User?

相关标签:
5条回答
  • 2020-11-30 03:14

    You can use the Module#const_get method. Example:

    irb(main):001:0> ARGV
    => []
    irb(main):002:0> Kernel.const_get "ARGV"
    => []
    
    0 讨论(0)
  • 2020-11-30 03:17

    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
    
    0 讨论(0)
  • 2020-11-30 03:24
    Object.const_get("User")
    

    No need to require ActiveSupport.

    0 讨论(0)
  • 2020-11-30 03:28

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

    "User".constantize
    
    0 讨论(0)
  • 2020-11-30 03:29

    Use ruby magic method: eval():

    eval("User")  #=>  User
    
    0 讨论(0)
提交回复
热议问题