SlideShare a Scribd company logo
1 of 3
Download to read offline
RUBY MODULES AND MIXINS
http://www.tutorialspoint.com/ruby/ruby_modules.htm                                             Copyright © tutorialspoint.com



Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.

       Modules provide a namespace and prevent name clashes.

       Modules implement the mixin facility.

Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about
being stepped on by other methods and constants.

Syntax:

 module Identifier
    statement1
    statement2
    ...........
 end


Module constants are named just like class constants, with an initial uppercase letter. The method definitions look
similar, too: module methods are defined just like class methods.

As with class methods, 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.

Example:

 #!/usr/bin/ruby

 # Module defined in trig.rb file

 module Trig
    PI = 3.141592654
    def Trig.sin(x)
    # ..
    end
    def Trig.cos(x)
    # ..
    end
 end


We can define one more module with same function name but different functionality:

 #!/usr/bin/ruby

 # Module defined in moral.rb file

 module Moral
    VERY_BAD = 0
    BAD = 1
    def Moral.sin(badness)
    # ...
    end
 end


Like class methods, whenever you define a method in a module, you specify the module name followed by a dot and
then the method name.
Ruby require Statement:

The require statement is similar to the include statement of C and C++ and the import statement of Java. If a third
program wants to use any defined module, it can simply load the module files using the Ruby require statement:

Syntax:

 require filename


Here it is not required to give .rb extension along with a file name.

Example:

 require 'trig.rb'
 require 'moral'

 y = Trig.sin(Trig::PI/4)
 wrongdoing = Moral.sin(Moral::VERY_BAD)


IMPORTANT: Here both the files contain same function name. So this will result in code ambiguity while including in
calling program but modules avoid this code ambiguity and we are able to call appropriate function using module name.

Ruby include Statement:

You can embed a module in a class. To embed a module in a class, you use the include statement in the class:

Syntax:

 include modulename


If a module is defined in separate file then it is required to include that file using require statement before embeding
module in a class.

Example:

Consider following module written in Week.rb file.

 module Week
    FIRST_DAY = "Sunday"
    def Week.weeks_in_month
       puts "You have four weeks in a month"
    end
    def Week.weeks_in_year
       puts "You have 52 weeks in a year"
    end
 end


Now you can include this module in a class as follows:

 #!/usr/bin/ruby
 require "Week"

 class Decade
 include Week
    no_of_yrs=10
    def no_of_months
       puts Week::FIRST_DAY
       number=10*12
       puts number
    end
end
 d1=Decade.new
 puts Week::FIRST_DAY
 Week.weeks_in_month
 Week.weeks_in_year
 d1.no_of_months


This will produce following result:

 Sunday
 You have four weeks in a month
 You have 52 weeks in a year
 Sunday
 120


Mixins in Ruby:

Before going through this section, I assume you have knowledge of Object Oriented Concepts.

When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.

Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they
pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.

Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out
when the code in the mixin starts to interact with code in the class that uses it.

Let us examine the following sample code to gain an understand of mixin:

 module   A
    def   a1
    end
    def   a2
    end
 end
 module   B
    def   b1
    end
    def   b2
    end
 end

 class Sample
 include A
 include B
    def s1
    end
 end

 samp=Sample.new
 samp.a1
 samp.a2
 samp.b1
 samp.b2
 samp.s1


Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes
both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can
see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance
or a mixin.

More Related Content

What's hot

Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in JavaJava2Blog
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & PackagesArindam Ghosh
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)Narayana Swamy
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
4- Inheritance, Aggregation, Encapsulation and Overloading
4- Inheritance, Aggregation, Encapsulation and Overloading4- Inheritance, Aggregation, Encapsulation and Overloading
4- Inheritance, Aggregation, Encapsulation and OverloadingGhadeer AlHasan
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overridingJavaTportal
 
Class notes(week 7) on packages
Class notes(week 7) on packagesClass notes(week 7) on packages
Class notes(week 7) on packagesKuntal Bhowmick
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in javasureshraj43
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23myrajendra
 

What's hot (20)

Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & Packages
 
JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
 
Java interface
Java interfaceJava interface
Java interface
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
4- Inheritance, Aggregation, Encapsulation and Overloading
4- Inheritance, Aggregation, Encapsulation and Overloading4- Inheritance, Aggregation, Encapsulation and Overloading
4- Inheritance, Aggregation, Encapsulation and Overloading
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java packages
Java packagesJava packages
Java packages
 
java packages
java packagesjava packages
java packages
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
Class notes(week 7) on packages
Class notes(week 7) on packagesClass notes(week 7) on packages
Class notes(week 7) on packages
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23
 

Similar to 13 ruby modules

Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.pptSeethaDinesh
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en inglesMarisa Torrecillas
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012skinandbones
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patternsGomathiNayagam S
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196Mahmoud Samir Fayed
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceEng Teong Cheah
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer ProgrammingInocentshuja Ahmad
 

Similar to 13 ruby modules (20)

Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.ppt
 
05 ruby classes
05 ruby classes05 ruby classes
05 ruby classes
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en ingles
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patterns
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Inheritance
InheritanceInheritance
Inheritance
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Only oop
Only oopOnly oop
Only oop
 

More from Walker Maidana (20)

20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
 
19 ruby iterators
19 ruby iterators19 ruby iterators
19 ruby iterators
 
18 ruby ranges
18 ruby ranges18 ruby ranges
18 ruby ranges
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
 
16 ruby hashes
16 ruby hashes16 ruby hashes
16 ruby hashes
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
 
14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
 
12 ruby blocks
12 ruby blocks12 ruby blocks
12 ruby blocks
 
11 ruby methods
11 ruby methods11 ruby methods
11 ruby methods
 
10 ruby loops
10 ruby loops10 ruby loops
10 ruby loops
 
09 ruby if else
09 ruby if else09 ruby if else
09 ruby if else
 
08 ruby comments
08 ruby comments08 ruby comments
08 ruby comments
 
07 ruby operators
07 ruby operators07 ruby operators
07 ruby operators
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
 
03 ruby environment
03 ruby environment03 ruby environment
03 ruby environment
 
01 index
01 index01 index
01 index
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
02 ruby overview
02 ruby overview02 ruby overview
02 ruby overview
 
21 ruby exceptions
21 ruby exceptions21 ruby exceptions
21 ruby exceptions
 

13 ruby modules

  • 1. RUBY MODULES AND MIXINS http://www.tutorialspoint.com/ruby/ruby_modules.htm Copyright © tutorialspoint.com Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits. Modules provide a namespace and prevent name clashes. Modules implement the mixin facility. Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about being stepped on by other methods and constants. Syntax: module Identifier statement1 statement2 ........... end Module constants are named just like class constants, with an initial uppercase letter. The method definitions look similar, too: module methods are defined just like class methods. As with class methods, 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. Example: #!/usr/bin/ruby # Module defined in trig.rb file module Trig PI = 3.141592654 def Trig.sin(x) # .. end def Trig.cos(x) # .. end end We can define one more module with same function name but different functionality: #!/usr/bin/ruby # Module defined in moral.rb file module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) # ... end end Like class methods, whenever you define a method in a module, you specify the module name followed by a dot and then the method name.
  • 2. Ruby require Statement: The require statement is similar to the include statement of C and C++ and the import statement of Java. If a third program wants to use any defined module, it can simply load the module files using the Ruby require statement: Syntax: require filename Here it is not required to give .rb extension along with a file name. Example: require 'trig.rb' require 'moral' y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD) IMPORTANT: Here both the files contain same function name. So this will result in code ambiguity while including in calling program but modules avoid this code ambiguity and we are able to call appropriate function using module name. Ruby include Statement: You can embed a module in a class. To embed a module in a class, you use the include statement in the class: Syntax: include modulename If a module is defined in separate file then it is required to include that file using require statement before embeding module in a class. Example: Consider following module written in Week.rb file. module Week FIRST_DAY = "Sunday" def Week.weeks_in_month puts "You have four weeks in a month" end def Week.weeks_in_year puts "You have 52 weeks in a year" end end Now you can include this module in a class as follows: #!/usr/bin/ruby require "Week" class Decade include Week no_of_yrs=10 def no_of_months puts Week::FIRST_DAY number=10*12 puts number end
  • 3. end d1=Decade.new puts Week::FIRST_DAY Week.weeks_in_month Week.weeks_in_year d1.no_of_months This will produce following result: Sunday You have four weeks in a month You have 52 weeks in a year Sunday 120 Mixins in Ruby: Before going through this section, I assume you have knowledge of Object Oriented Concepts. When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance. Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin. Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it. Let us examine the following sample code to gain an understand of mixin: module A def a1 end def a2 end end module B def b1 end def b2 end end class Sample include A include B def s1 end end samp=Sample.new samp.a1 samp.a2 samp.b1 samp.b2 samp.s1 Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance or a mixin.