我试图修改现有的ruby代码,ruby不是我的第一个languange。部分代码如下:
#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
不知怎的,我无法访问somefunction()
中的方法anotherfunction
。
如何在模块C内的方法中访问模块B中定义的方法?为什么它不起作用?
答案 0 :(得分:0)
假设您想要自己调用模块函数,首先需要使它们成为模块函数(在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
答案 1 :(得分: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"