- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Difference between Python and Ruby
- Difference between #include and #include "filename" in C/C++?
- What is the difference between #include and #include “filename”?
- Difference between .extend() / .assign() and .merge() in Lodash library.
- What is the difference between include action and include directive in JSP?
- 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
- Extend data class in Kotlin
- Array push(), pop() and clear() functions in Ruby
- Thread life cycle and its states in Ruby
- How to Read and Writes Files in Ruby
- Comparable module in Ruby
