What is the difference between nesting module definitions and using :: in a ruby ​​definition?

What is the difference between this:

module Outer module Inner class Foo end end end 

and this:

 module Outer::Inner class Foo end end 

I know that the last example will not work if Outer not been defined before, but there are some other differences with a constant scope, and I could find their description in SO or in the documentation (including the Ruby book Program)

+6
source share
2 answers

there is at least one differential - constant search, check this code:

 module A CONST = 1 module B CONST = 2 module C def self.const CONST end end end end module X module Y CONST = 2 end end module X CONST = 1 module Y::Z def self.const CONST end end end puts A::B::C.const # => 2, CONST value is resolved to A::B::CONST puts X::Y::Z.const # => 1, CONST value is resolved to X::CONST 
+3
source

Thanks to keymone answer, I formulated the correct Google query and found this: Module.nesting and persistent name resolution in Ruby

Using :: changes the resolution of the constant area.

 module A module B module C1 # This shows modules where ruby will look for constants, in this order Module.nesting # => [A::B::C1, A::B, A] end end end module A module B::C2 # Skipping A::B because of :: Module.nesting # => [A::B::C2, A] end end 
+7
source

Source: https://habr.com/ru/post/920022/


All Articles