微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 通过字符串在模块中创建类的实例

假设我在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在控制台中工作时失败?
我也尝试过Object.const_get(‘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获得

原文地址:https://www.jb51.cc/ruby/269229.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐