Chronicling My Ruby on Rails Journey

March 8, 2007

Nested Modules

Filed under: Module — Bob Ngu @ 9:29 pm

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 Comments »

  1. 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.

    Comment by el raichu — March 9, 2007 @ 3:39 am | Reply

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

    Comment by bngu — March 9, 2007 @ 9:31 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.