Mixin in Ruby

C++ allows developers to use multiple inheritance. Unlike C++, Ruby only allows developers to use single inheritance. But Ruby has mixin functionality, which allows code to be included from other modules.

Here’s sample code to demonstrate mixin:

module MixinFirst
	def mixin_first_display
		puts "This is mixin first"
	end
end

module MixinSecond
	def mixin_second_display
		puts "This is mixin second"
	end
end

class Base
	def inheritance_display
		puts "This is inheritance"
	end
end

class Child < Base
	include MixinFirst
	include MixinSecond
end

child = Child.new
child.mixin_first_display
child.mixin_second_display
child.inheritance_display

Sample result:

This is mixin first
This is mixin second
This is inheritance
Leave a comment

0 Comments.

Leave a Reply

( Ctrl + Enter )