简体   繁体   English

在模块中评估,但类不是模块的一部分

[英]Eval in a module, but the class is not part of the module

I have a module Database . 我有一个Database模块。 In this module, eval("MyClass") returns Database::MyClass is inexistent . 在此模块中, eval("MyClass")返回Database::MyClass is inexistent But I want it to be evaluated outside of the Database module. 但是我希望在Database模块之外对其进行评估。 Who knows how this is to be done? 谁知道该怎么做?

您应该尝试然后显式指定全局范围:

eval('::MyClass')

If you are trying to access a class by its name contained in a string, it might be a better choice to use Kernel.const_get. 如果您尝试通过包含在字符串中的名称访问类,则使用Kernel.const_get可能是更好的选择。 See this stack overflow post for more info: Get a class by name in Ruby? 有关更多信息,请参见此堆栈溢出文章: 在Ruby中按名称获取类?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM