
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Include and Extend in Ruby
In Ruby, when we are using the include keyword, we are importing a module code, but we aren't allowed to access the methods of the imported modules with the class directly because it basically gets imported as a subclass for the superclass.
On the other hand, when we are using the extend keyword in Ruby, we are importing the module code but the methods are imported as class methods. If we try to access the methods that we imported with the instance of the class, the compiler will throw an error.
Now let's use these two keywords in a Ruby code to understand the difference.
Example 1
Consider the code shown below.
# Creating a module that contains a method module MyModule def first_method puts 'This is the First Method.' end end class First_Class include MyModule end class Second_Class extend MyModule end # object access First_Class.new.first_method # class access Second_Class.first_method
Output
It will produce the following output.
This is the First Method. This is the First Method.
Example 2
Now let's consider a case where we would want to import instance methods on a class and its class methods as well. In such a case, we will use both include and extend keywords at the same time.
Consider the code shown below
# Creating a module that contains a method module MyModule def logs(x) puts x end end class First_Class include MyModule extend MyModule end First_Class.new.logs("It's a chilly overcast day.") First_Class.logs("Keep an umbrella with you.")
Output
It will produce the following output.
It's a chilly overcast day. Keep an umbrella with you.