Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby模块中模块的访问方法_Ruby_Module - Fatal编程技术网

ruby模块中模块的访问方法

ruby模块中模块的访问方法,ruby,module,Ruby,Module,我试图修改现有的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 e

我试图修改现有的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
#someFile1.rb
模块A
模块B
def somefunction()
终止
终止
终止
类X::Y
包括A::B
终止
#someFile2.rb
模块A
模块C
def另一个函数()

#somefunction()假设您希望自己调用模块函数,那么首先需要将它们设置为模块函数(在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

在将模块中的实例方法混合到一个类中并创建该类的对象之前,通常无法访问它们

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"

情况尚不清楚。您需要添加更多内容以澄清。@sawa我已经更新了问题,还不清楚吗?谢谢您的回答,我已经更新了我的问题。我还试图将模块B和C都包含在类X中,但没有成功。错误是
未初始化常量A::B
知道为什么吗?听起来好像您不需要包含
A::B
的文件。更新问题中的代码不起作用的原因是您没有包含
A::B
,因此
X
中没有该方法。