Ruby - Module Mix-Ins

Introduction

Ruby doesn't support multiple inheritance.

One class cannot inherit from multiple classes at the same time.

To share functionality between disparate classes, you can use modules.

Modules act like a sort of "super" class and can be included into other classes, extending that class with the methods the module offers.

For example:

Demo

module UsefulFeatures 
  def class_name 
    self.class.to_s 
  end #   w  w  w  .  jav  a2s . c  o  m
end 

class Person 
  include UsefulFeatures 
end 

x = Person.new 
puts x.class_name

Result

Here, UsefulFeatures looks almost like a class.

Modules are organizational tools rather than classes.

The class_name method exists within the module, and is then included into the Person class.

Here's another example:

Demo

module AnotherModule 
  def do_stuff #  w  w  w .ja  v a  2s  . com
    puts "This is a test" 
  end 
end 

include AnotherModule 
do_stuff

Result

Here, you can include module methods in the current scope, even if you're not directly within a class.

It is like a class and you can use the methods directly:

AnotherModule.do_stuff 

include takes a module and includes its contents into the current scope.

Related Topics