Chronicling My Ruby on Rails Journey

Nested Modules

Posted by: Bob Ngu on: March 8, 2007

My RoR efforts have culminated in JiggyMe, check it out!

An example of nested modules,

“moduletest.rb”

module M
    def report
    puts "'report' method in module M"
  end
end

module N
  module J
    def report
      puts "'report' method in module J"
    end
  end
  def report
    puts "'report' method in module N"
  end
end

To get to report method in module J, module N has to be included first

require 'moduletest'

class C
  include N
  include J
end

a = C.new
a.report

If module N is not included first, you will get an error like this

eg4.rb:7: uninitialized constant C::J (NameError)

2 Responses to "Nested Modules"

hmm, tried the following snippet on Try Ruby (http://tryruby.hobix.com).

class C
include N::J
end

a = C.new
a.report #prints “report” of j

I typed in the contents of moduletest.rb first.

Yep, that works too, a more succinct alternate way of doing the same thing.

Leave a Reply