6

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)

4

2 回答 2

7

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
于 2012-07-09T10:59:05.297 回答
3

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
于 2012-07-09T10:38:50.923 回答