Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 809
Valentin Nemcev Avatar asked Jul 09 '12 10:07

Valentin Nemcev


2 Answers

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
like image 95
Valentin Nemcev Avatar answered Sep 30 '22 00:09

Valentin Nemcev


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
like image 26
keymone Avatar answered Sep 29 '22 23:09

keymone