Ruby Modules and Classes

It can be confusing to keep track of Ruby namespaces when there are nested modules and classes. This post will display several code snippets with embedded questions. Answers are underneath the code snippets.

module Wrapper
  class Person
    def hi
      "HIHIHIHIH"
    end
  end
end
# Call the Person#hi method outside of the Wrapper namespace

To call the Person#hi method outside of the Wrapper namespace (aka Module), replace the comment with this code: p Wrapper::Person.new.hi

How does the Person#hi method get called inside the Wrapper namespace?

module Wrapper
  class Person
    def hi
      "HIHIHIHIH"
    end
  end
  # Call the Person#hi method inside the Wrapper namespace
end

Since we are calling the method within the Wrapper module, we can either replace the comment with p Wrapper::Person.new.hi (as in the previous example) or simply use p Person.new.hi as the Wrapper namespace is implied.

The code in the following example is slightly changed to demonstrate how to call a method that is defined in a Module in a class.

module Wrapper
  module Helper
    # Create a method called sup that returns "A YO!"
  end
  class Person
    def hi
      Helper::sup
    end
  end
end
p Wrapper::Person.new.hi

Replace the comment with the following code:

def self.sup
  "A YO!"
end

Constants also have unique behavior when namespaced in classes. Add code to access the GREETINGS constant in the Person#hi method.

module Wrapper
  module Helper
    GREETINGS = "Hello friend"
  end
  class Person
    def hi
      # Call the GREETINGS constant in this method
    end
  end
end
p Wrapper::Person.new.hi

Simply replace the comment with Helper::GREETINGS to access the constant in the hi method.

Access the GREETINGS constant in the Person#hi method with the Helper module removed.

module Wrapper
  GREETINGS = "Hello friend"
  class Person
    def hi
      # Call the GREETINGS constant in this method
    end
  end
end
p Wrapper::Person.new.hi

The GREETINGS constant is now accessible throughout the Wrapper namespace with GREETINGS (i.e. replace the comment with GREETINGS).

In a future post, I will describe how to use the project’s module/class structure to create a corresponding file structure for the code.

Advertisements

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 )

Google+ photo

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

Connecting to %s