ruby 遇到“include module”时会包含什么?陈述?
如果我有以下项目结构
project/ lib/ subproject/ a.rb b.rb lib.rb
,其中 lib.rb 如下所示:-
module Subproject
def foo
do_some_stuff
end
end
并且 a.rb 和 b.rb 都需要在 lib.rb 中混合一些方法,并且都在模块中命名,如下所示:-
require 'subproject/lib'
module Subproject
class A
include Subproject
def initialize()
foo()
end
end
end
ruby 在什么情况下会做什么它遇到包含语句吗?它怎么知道我只想包含 lib.rb 中的 mixin 而不是包含 A 类和 B 类的整个模块,这纯粹是基于 subproject/lib 的需求还是我弄错了?包括整个模块,包括A类和B类本身的定义?
If I have the following project structure
project/ lib/ subproject/ a.rb b.rb lib.rb
where lib.rb looks like this :-
module Subproject
def foo
do_some_stuff
end
end
and a.rb and b.rb both need to mixin some methods within lib.rb and are both namespaced within a module like so :-
require 'subproject/lib'
module Subproject
class A
include Subproject
def initialize()
foo()
end
end
end
What does ruby do when it encounters the include statement? How does it know that I want to only include the mixin from lib.rb rather than the whole module which includes both class A and class B, is this based purely on the require of subproject/lib or am I getting it wrong and it is including the whole of the module, including the definitions of Class A and B within themselves?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它包括整个模块。只有一个
Subproject
模块,您刚刚在a.rb
和b.rb
中重新打开它并添加了类A< /code> 和
B
。我认为require
无论如何都没有相关性。顺便说一句,您随时可以在 irb 中尝试一下:
It is including the whole of the module. There is only one
Subproject
module, you've just reopened it ina.rb
andb.rb
and added classesA
andB
to it. I don't thinkrequire
is related anyhow there.BTW, you can always try it out in
irb
: