ruby – 通过字符串在模块中创建类的实例
发布时间:2020-12-17 04:31:25 所属栏目:百科 来源:网络整理
导读:假设我在test.rb中有这个 Ruby代码 module MyModule class TestClassA end class TestClassB def initialize a = Object.const_get('MyModule::TestClassA').new end endend 在这里,ruby shell中的一些测试以irb -r test.rb开头: ruby-1.8.7-p302 MyModule
假设我在test.rb中有这个
Ruby代码
module MyModule class TestClassA end class TestClassB def initialize a = Object.const_get('MyModule::TestClassA').new end end end 在这里,ruby shell中的一些测试以irb -r test.rb开头: ruby-1.8.7-p302 > MyModule => MyModule ruby-1.8.7-p302 > MyModule::TestClassA => MyModule::TestClassA ruby-1.8.7-p302 > MyModule::TestClassA.new => #<MyModule::TestClassA:0x10036bef0> ruby-1.8.7-p302 > MyModule::TestClassB => MyModule::TestClassB ruby-1.8.7-p302 > MyModule::TestClassB.new NameError: wrong constant name MyModule::TestClassA from ./test.rb:7:in `const_get' from ./test.rb:7:in `initialize' from (irb):1:in `new' from (irb):1 为什么TestClassB的构造函数中的Object.const_get(‘MyModule :: TestClassA’).new在MyModule :: TestClassA.new在控制台中工作时失败? 解决方法
没有名为“MyModule :: TestClassA”的常量,在名为MyModule的常量中有一个名为TestClassA的常量.
尝试: module MyModule class TestClassA end class TestClassB def initialize a = Object.const_get("MyModule").const_get("TestClassA").new end end end 至于为什么它不起作用,这是因为::是一个运算符而不是命名约定. 其他示例和信息可在http://www.ruby-forum.com/topic/182803获得 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 使用wsDualHttpBinding超时通过Internet连接到WCF服务
- OPENXML解析sp_xml_preparedocument获取的XML句柄
- 基于Stratus service在flash player10中用RTMFP开发点对点应
- 从C调用它时指定Python模块的目录
- dojo小例子(16)Grid cell里显示图片,图片取自rest
- Char不在C中的多维数组中工作.需要澄清
- vue router仿天猫底部导航栏功能
- pgsql 的 max_fsm_pages
- 【Android UI】案例04配置控件点击效果(selector)
- objective-c – 典型的Objective C消息实现