【问题标题】:What is the issue with the method acces in ancestors chain in RubyRuby祖先链中的方法访问有什么问题
【发布时间】:2013-12-21 20:57:29
【问题描述】:

我已经定义了一个方法,其中包含很少的类和很少的模块。从其中一个类中,我尝试调用在模块中定义的方法(在公共模块中),但出现访问错误。这是完整的层次结构:

module Top
 class NestedClass
   #some code
   NestedModule::method_name
 end

 module NestedModule
   def method_name
     #some code
   end
 end
end

我得到的错误是:Top::NestedModule:Module 的未定义方法 'method_name'

【问题讨论】:

    标签: ruby class module hierarchy ancestor


    【解决方案1】:

    写成:

    module Top
      module NestedModule
        def self.method_name
          #some code
        end
      end
      class NestedClass
        #some code
        NestedModule::method_name
      end
    end
    

    在您的情况下,您在定义模块 NestedModule 之前做了 NestedModule::method_name

    【讨论】:

    • 如果我在 Top 模块之外定义它并将它包含在我真正需要它的类(NestedClass)中怎么办?
    • @user2128702 我没听懂你
    • 我尝试了你的方法,但我得到了完全相同的 NoMethodError。我真的不知道为什么。
    • 看来里面的所有方法都得是'self'。
    【解决方案2】:

    您不能直接调用未声明的方法以及实例模块方法。 也许这会为你解决问题:

    module Top
      module NestedModule
        def self.module_method
          1
        end
    
        def instance_method
          2
        end
      end
    
      class NestedClass
        NestedModule.module_method # => 1
        NestedModule.instance_method(:instance_method) # => #<UnboundMethod: Top::NestedModule#instance_method>
    
        extend NestedModule
        instance_method # => 2
    
        include NestedModule
        new.instance_method # => 2
      end
    end
    

    虽然“NestedModule::module_method”在这里也可以使用,但惯例是在调用类/模块方法时使用点,在访问嵌套模块/类时使用双冒号。

    【讨论】:

      猜你喜欢
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 2011-06-09
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多