Ruby Mixin
Introduction
Though Ruby is an object oriented language, it doesnot support multiple inheritance. So, only single inheritance is possible in Ruby.
To support inheritance, mixin comes into play. Mixin is set of code wrapped up in a module that a class can include
or extend
. To use mixins
mainly two keywords are used, include
and extend
. It is the concept of inheriting everything defined in a module into a class that includes or
extends module including methods(private, protected, public), attributes (attr_accessor :name) and constants. In addition, a class can have multiple
mixins.
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module Month
def weeks_in_month
puts "You have four weeks in a month"
end
def months_in_year
puts "You have 12 months in a year"
end
end
class Year
include Month
def no_of_weeks x
puts "There are #{x} number of weeks in a year"
end
end
y1 = Year.new
y1.weeks_in_month
y1.months_in_year
y1.no_of_weeks 4
Output:
You have four weeks in a month
You have 12 months in a year
There are 4 number of weeks in a year
include vs extend
If include
keyword is used the methods within module acts as instance method in current class. But using extend
keyword the methods
act as class method. So, while accessing instance method we need to instantiate the class whereas to use class method we can just access through
the class itself. Here is an example that shows how the class and instance methods can be called.
Class methods VS Instance methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class SayHello
def self.from_the_class
"Hello, from a class method"
end
def from_an_instance
"Hello, from an instance method"
end
end
Result:
SayHello.from_the_class
=> "Hello, from a class method"
SayHello.from_an_instance
=> undefined method `from_an_instance' for SayHello:Class
hello = SayHello.new
hello.from_the_class
=> undefined method `from_the_class' for #<SayHello:0x0000557920dac930>
hello.from_an_instance
=> "Hello, from an instance method"
Summary
Ruby mixin is the easiest way to add functionality to classes. It is more powerful than inheritance in terms of usage. So, it is the best way to inherit features in Ruby.