简体   繁体   中英

ruby module inside module

I have a ruby module which includes many other modules. Here's a quick example:

module Foo

  module Bar
  end

  module Baz
  end

end

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM