Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The keywords <strong>class</strong>, <strong>module</strong> and <strong>def</strong> are what is known as "scope gates". They create new scopes. </p> <pre><code>#!/usr/bin/env ruby module ModuleA class ClassA def initialize puts "test passed" end end end module ModuleB include ModuleA # test 1 c = ClassA.new # this works as ModuleA has been included into this module class ClassB # class is a scope gate, creates new scope def initialize # def is a scope gate, creates new scope c = ModuleA::ClassA.new # must fully qualify ClassA end end ClassB2 = Class.new do # no scope gate define_method :initialize do # no scope gate c = ClassA.new # this works, no need to fully qualify end end end b = ModuleB::ClassB.new b2 = ModuleB::ClassB2.new </code></pre> <p>I began to understand scopes in Ruby after reading the <a href="http://rads.stackoverflow.com/amzn/click/1934356476">book "Metaprogramming Ruby"</a>. It is truly enlightening.</p> <p><strong>Edit</strong>: In response to also's comment below.</p> <p>A class is essentially a Ruby constant (notice that it is an object with a capitalized name). Constants have a defined lookup algorithm within scopes. <a href="http://rads.stackoverflow.com/amzn/click/0596516177">The Ruby Programming Language</a> O'Reilly book explains it well in section 7.9. It is also briefly described in this <a href="http://coderrr.wordpress.com/2008/03/11/constant-name-resolution-in-ruby/">blog post</a>.</p> <p>Top-level constants, defined outside of any class or module, are like top-level methods: they are implicitly defined in Object. When a top-level constant is referenced from within a class it is resolved during the search of the inheritance hierarchy. If the constant is referenced within a module definition it does an explicit check of Object after searching the ancestors of the module. </p> <p>That's why include ModuleB at the top level makes the class in ModuleB visible in all modules, classes and methods. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload