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.

Updated on: 12-Apr-2022

974 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements