红宝石模块在模块内部 [英] ruby module inside module
问题描述
我有一个ruby模块,其中包括许多其他模块.这是一个简单的示例:
I have a ruby module which includes many other modules. Here's a quick example:
module Foo
module Bar
end
module Baz
end
end
除了,我在Foo模块中有6-7个模块.有没有一种方法可以将Bar/Baz放在单独的文件中,但仍然得到相同的行为?现在,我所有的代码都放在1个文件中,非常无组织.
except, I have like 6-7 modules inside Foo module. Is there a way I can put Bar/Baz in separate file but still get the same behavior? Right now all my code is inside 1 file, very unorganized.
推荐答案
您可以这样定义它们,每个都在单独的文件中
You can define them like this, each in a separate file:
# foo.rb
module Foo
end
# foo_bar.rb
module Foo::Bar
end
# foo_baz.rb
module Foo::Baz
end
NB.您必须先定义Foo
模块 ,然后才能使用此符号定义诸如Foo::Bar
之类的模块.
NB. You will need to define the Foo
module before being able to define modules such as Foo::Bar
with this notation.
或者您可以将它们以当前使用的格式放入不同名称的文件中,并且仍然可以使用:
Or you could just put them in differently named files in the format they're currently in and it should still work:
# foo_bar.rb
module Foo
module Bar
end
end
# foo_baz.rb
module Foo
module Baz
end
end
这篇关于红宝石模块在模块内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!