Q:

Ruby program to include a module inside the class

belongs to collection: Ruby Modules and Mixins Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby program to create a nested module... >>
<< Ruby program to create a module with variables...