Ruby (and Rails) nested module syntax

前端 未结 4 1880
梦如初夏
梦如初夏 2020-12-29 03:09

I\'m wondering what the difference is between the following two modules

# First Example
module Parent
  module Child
  end
end

and

4条回答
  •  不知归路
    2020-12-29 03:47

    It seems that Banister's answer is also the reason for this behaviour:

    ruby-1.9.2-p290 :001 > module A; module A; A.ancestors; end; end
     => [A::A] 
    ruby-1.9.2-p290 :002 > module A::A; A.ancestors; end
     => [A] 
    

    The inner module A is a constant inside the outer module A, and thus it's not visible using the second method.

    Editing my previous comment:

    This is explained in 7.9 "Constant Lookup" of "The Ruby Programming Language" (First Edition). The relevant part here is Module.nesting, which doesn't contain the outer module in the second example, thus A can only be found in the global scope.

提交回复
热议问题