Modules and Namespaces in Ruby

Ruby modules can act in two apostasies. They can group classes, modules, constants and act as namespaces. Math module is a good example of such a namespace with such known constants as Math:PI. Modules are also used as package for follow-up usage inside classes.

It is interesting to note that Module is a superclass of Class which makes every class also a module. The main difference between Ruby modules and classes is in impossibility to declare objects from it. So, we will never be able to call new on the module.

Math.new //will produce “undefined method new” error message

Modules are ideal for creating functionality that can be included in other classes and often times used to overcome Ruby’s lack of support for multiple inheritance.

class MyClass < String
 include MyModule
end

We can see from the example above, that MyClass is a subclass of String and has access to String methods as well as capable of using MyModule methods at the same time. In other word, Ruby allows to have only one superclass but multiple modules which makes it very flexible for developers.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…