访问模块ruby模块中的方法
问题描述:
我想修改现有的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中定义的方法?为什么它不起作用?
答
实例方法不是一般的访问,直到你将它们混合成一类,并创建一个类的对象。
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"
答
假设你想自己调用模块函数,首先需要使它们成为模块函数(在Java中考虑static
或在C++中考虑namespace
)。然后您可以使用::
(名称空间分辨率)运算符。请参阅foo
和bar
。
如果您想将它们导入到类中,只需导入它们,两者都将可见。见baz
和qux
。
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
情况不明确。您需要添加更多才能清楚。 – sawa 2014-10-02 10:07:00
@sawa我已经更新了这个问题,现在还不清楚吗? – dieend 2014-10-03 02:22:59