Convert string to class name without using eval in ruby?

后端 未结 2 2021
庸人自扰
庸人自扰 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: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
    

提交回复
热议问题