Convert string to class name without using eval in ruby?

后端 未结 2 2036
庸人自扰
庸人自扰 2020-12-31 09:41

I have something like this:

string = \"Post\"

I would like to convert the string to a class name literal. I use eval like this to convert t

相关标签:
2条回答
  • 2020-12-31 10:13

    You can try

    class Post
    end
    
    Object.const_get("Post")
    

    Which returns the Post class

    0 讨论(0)
  • 2020-12-31 10:17

    Use Module.const_get

    string = "Fixnum"
    clazz = Object.const_get(string)
    clazz.name # => "Fixnum"
    

    If you are in a rails context, you can also use the `#constantize method on string

    clazz = string.constantize # => Fixnum
    
    0 讨论(0)
提交回复
热议问题