

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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.
- Related Questions & Answers
- Difference between .extend() / .assign() and .merge() in Lodash library.
- What is the difference between include action and include directive in JSP?
- Difference between #include <filename> and #include "filename" in C/C++?
- What is the difference between #include <filename> and #include “filename”?
- append() and extend() in Python
- append() and extend() in Python program
- True, False and Nil in Ruby Programming
- Hash select() and select!() methods in Ruby
- Unless statement and Unless modifier in Ruby
- Difference between == and === operator in JavaScript
- Difference between !== and ==! operator in PHP
- Difference between . and : in Lua programming
- Difference between JCoClient and JCoDestination
- Difference between String and StringBuffer.
- Difference between StringBuffer and StringBuilder.