Alle lunedì 2 aprile 2007, Ken Mitchell ha scritto:
> I have what I feel should be a simple issue.  Look at the following:
>
> ############################
> # Test of nested modules/classes
> ############################
> class Global
>   module TestMod
>     TEST = "test1"
>     def print_test
>       puts "test2"
>     end
>   end#module TestMod
>
>   include TestMod
>   puts TEST
>   print_test
>
> end#class Global
> ##############################
>
> ->test1
> ->test.rb:22: undefined local variable or method 'print_test' for
> Global:Class
>
> Whether "Global" is a Class or a Method the same happens.  However, if I
> comment out "Global" completely, out put is as expected:
>
> ->test1
> ->test2
>
> Thanks in advance.

When you include TestMod in the class Global, the instance methods of TestMod 
become instance methods of Global, that is, they become methods of the 
instances of Global, not of Global itself. So, you can do:

Global.new.print_test
=> "test2"

The same happens if Global were a module.

If you want to add the instance methods of TestMod to Global itself, instead, 
you can do the following:

class Global
  module TestMod
    ...
  end #End of TestMod
  extend TestMod
end

While Module#include adds the instance methods of the module as instance 
methods of the class (or module) where it's called, extend adds the instance 
methods of the module to its receiver (self, in this case).

I hope this helps

Stefano