2014-10-02 108 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