2014-10-02 137 views
0

我想修改现有的ruby代码,而ruby不是我的第一个语言。该部分代码如下图所示:访问模块ruby模块中的方法

#someFile1.rb 
module A 
    module B 
    def somefunction() 
    end 
    end 
end 

class X::Y 
    include A::B 
end 


#someFile2.rb  
module A 
    module C 
    def anotherfunction() 
     #somefunction() <-- error 
    end 
    end 
end 
class X::Y 
    include A::C 
end 

不知怎的,我不能在anotherfunction访问方法somefunction()。 如何在模块C中的方法中访问模块B中定义的方法?为什么它不起作用?

+4

情况不明确。您需要添加更多才能清楚。 – sawa 2014-10-02 10:07:00

+0

@sawa我已经更新了这个问题,现在还不清楚吗? – dieend 2014-10-03 02:22:59

回答

0

实例方法不是一般的访问,直到你将它们混合成一类,并创建一个类的对象。

module A 
    module B 
    def some_method 
     "foo" 
    end 
    end 
end 

module A 
    module C 
    def another_method 
     some_method 
    end 
    end 
end 

class X 
    include A::B 
    include A::C 
end 

X.new.another_method 
# => "foo" 

但我会说这是不是很优雅有依赖于一个事实,即一些其他的模块也被混合到同一个对象模块

类方法的模块,在另一方面,可以这样访问:

module A 
    module B 
    def self.somefunction 
     "foo" 
    end 
    end 
end 

module A 
    module C 
    def self.another_function 
     A::B.somefunction 
    end 
    end 
end 

A::C.another_function 
# => "foo" 
+0

感谢您的回答,我已更新我的问题。我也尝试在类X中包含模块B和C,但无济于事。错误是'未初始化的常量A :: B'任何想法为什么? – dieend 2014-10-03 02:22:07

+0

这听起来像你没有要求包含'A :: B'的文件。更新问题中的代码不起作用的原因是您不包含'A :: B',因此该方法不存在于'X'中。 – Jesper 2014-10-03 06:32:28

0

假设你想自己调用模块函数,首先需要使它们成为模块函数(在Java中考虑static或在C++中考虑namespace)。然后您可以使用::(名称空间分辨率)运算符。请参阅foobar

如果您想将它们导入到类中,只需导入它们,两者都将可见。见bazqux

module A 
    module B 
    def self.foo 
     puts "foo" 
    end 

    def baz 
     puts "baz" 
    end 
    end 
end 

module A 
    module C 
    def self.bar 
     puts "bar" 
     A::B::foo 
    end 

    def qux 
     puts "qux" 
     baz 
    end 
    end 
end 

class X 
    include A::B 
    include A::C 
end 

A::C::bar 

x = X.new 
x.qux 

输出:模块

bar 
foo 
baz 
qux