Ruby program to include a module inside the class

Ruby Example: Write a program to include a module inside the class.
Submitted by Nidhi, on December 29, 2021

Problem Solution:

In this program, we will create a module with some methods. Then we will a create class and include the created module inside the class.

Program/Source Code:

The source code to include a module inside the class is given below. The given program is compiled and executed successfully.

# Ruby program to include a module 
# inside the class

module MyModule
    def Method1
        puts "Inside Method1";
    end
    
    def Method2
        puts "Inside Method2";
    end
    
    def Method3
        puts "Inside Method3";
    end
end

class MyClass
    include MyModule;
    def SayHello
        puts "Hello World";
    end
end
       
obj =  MyClass.new
       
obj.Method1(); 
obj.Method2(); 
obj.Method3(); 

obj.SayHello();

Output:

Inside Method1
Inside Method2
Inside Method3
Hello World

Explanation:

In the above program, we created a module MyModule with 3 methods. Then we created a class MyClass and include MyModule, and also defined a method SayHello(). After that, we created the object obj of class MyClass and called all methods.

Ruby Modules and Mixins Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.