ruby convert class name in string to actual class

后端 未结 6 1787
后悔当初
后悔当初 2020-12-12 20:03

How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)

The reason I ask is because I\'m us

6条回答
  •  不知归路
    2020-12-12 20:51

    When ActiveSupport is available (e.g. in Rails): String#constantize or String#safe_constantize, that is "ClassName".constantize.

    In pure Ruby: Module#const_get, typically Object.const_get("ClassName").

    In recent rubies, both work with constants nested in modules, like in Object.const_get("Outer::Inner").

提交回复
热议问题