What are the differences between this:
module Outer
module Inner
class Foo
end
end
end
and this:
module Outer::Inner
class Foo
end
end
I know the latter example won't work if Outer
was not defined earlier, but there are some other differences with constant scope and I could find their description on SO or in documentation (including Programming Ruby book)
Thanks to keymone's answer I formulated correct Google query and found this: Module.nesting and constant name resolution in Ruby
Using ::
changes constant scope resolution
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
there is at least one difference - constant lookup, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With