Shiva Kumar 's Blog

Start small,Think Big

Modules and Mixins

Ruby support inheritance,child class have all the property of parent class and access to their  methods.Some call parent class as superclass and child  as subclass.Below is the simple example for inheritance .In ruby we use less-than notation like Child < Parent like parent class pushing all the property to the  child.There is nice way to see the class ‘s parent class .Just ask the current class’s superclass Class.superclass . Keep asking for the superclass of the result you get .You find the hierarchy of class


Ruby does not support multiple inheritance.why? It can get confusing when both parents class have the same method name the child class do not know which method to use.So ruby introduce Modules.Also when you start writing more and more lines of code you see lot code gets repeated.Ruby is all about simplicity and keeping DRY(Don’t Repeat Yourself).We can put the comman piece of code in modules and include it in places you need .Modules are a way of grouping methods,classes and constants.It provides namespace and prevent name clashes and modules support mixin facility,which very interesting will come to that.Module defines a namespace where your method and constants can play without worrying about other method and classes being stepped in.


You call a module method by preceding its name with the module’s name and a period, and you reference a constant using the module name and two colons.The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included


Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for inheritance, providing a facility called a mixin.A module can’t have instances, because a module isn’t a class. However, you can include a module within a class definition. When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in.


Include statement has nothing to do with C #include.The Ruby include statement simply makes a reference to a module.If that module is in separate file,you must use require.True power of mixin comes out when the code in the mixin starts to interact with code in the class that uses it.

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">