【问题标题】:include part of ruby module hierarchy包含 ruby​​ 模块层次结构的一部分
【发布时间】:2015-01-16 20:35:17
【问题描述】:

如果我有一堆看起来像这样的类:

 module A
   module B
     module C
       module D
         class SpecificClass1
         end
       end
     end
   end
 end

我不想像这样引用类

 instance = A::B::C::D::SpecificClass1.new

一种方法是:

include A::B::C::D
instance = SpecificClass1.new

如果我想做这样的事情怎么办:

include A::B
instance = C::D::SpecificClass1.new

为什么这不起作用?它返回:

uninitialized constant C::D (NameError)

有没有办法有效地做我正在尝试的事情?

【问题讨论】:

  • 无法复制。
  • 顺便说一句,你有一个错字instance = C::D::SpecifiClass1.new。 SpecifiClass1 应该是 SpecificClass1
  • 嗯,我过于简单的例子确实有效。所以我在我“拆分”模块层次结构的地方移动,在某些情况下它可以工作!我有一种预感,因为此类中的另一个必需文件具有相同的后缀,因此存在名称冲突?
  • 我没有看到这个,也不知道这是不是一个好主意,但是你可以写def specific_class1_instance; eval "A::B::C::D::SpecificClass1.new"; end来启用(在类中添加def m; puts 'hi'; end之后)specific_class1_instance.m #=> hi。我认为您不必担心这里的评估警察。
  • @CarySwoveland 为什么要使用eval,因为你有合适的模块链,那么A::B::C::D::SpecificClass1.new 就可以了。

标签: ruby namespaces


【解决方案1】:

来自 irb 会话:

module A
  module B
    module C
      module D
        class SpecificClass1
        end
      end
    end
  end
end

=> nil 
2.1.0 :011 > A::B::C::D::SpecificClass1.new
=> #<A::B::C::D::SpecificClass1:0x0000010248f3c0> 
2.1.0 :012 > include A::B::C::D
=> Object 
2.1.0 :013 > instance = SpecificClass1.new
=> #<A::B::C::D::SpecificClass1:0x00000103803b40> 

2.1.0 :011 > include A::B
=> Object 
2.1.0 :012 > instance = C::D::SpecificClass1.new
=> #<A::B::C::D::SpecificClass1:0x0000010247b848> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 2019-06-15
    • 1970-01-01
    • 2011-06-16
    • 2019-11-20
    • 2023-02-14
    相关资源
    最近更新 更多