Difference between include, extend, require and load in ruby

First of all, include and extend are language-level methods where as require and load are file-level methods. But all methods are used to support DRY concept of Ruby. Will explain each of them with examples.

Include

include is used bringing all the methods of a module into the class as instance methods. These are mixins used in Ruby as it does not support Multiple inheritance.

module Animal

  def my_method
    puts "Hi, I am a #{self.class}"
  end

  def method_2
    puts "My dog's name is spike"
  end
end


class Dog
  include Animal

  def method_1
    puts "hey, I am faithful"
  end

end

Dog.new.method_1 # => “hey, I am faithful”
Dog.new.my_method # => “Hi, I am a Animal”
Dog.new.method_2 # => “My dog’s name is spike”

Extend

extend is used for bringing all the methods of a module into the class as class methods. Helps in keeping the code DRY.

module Animal

  def my_method
    puts "Hi, I am a #{self.class}"
  end

  def method_2
    puts "My dog's name is spike"
  end
end


class Dog
  extend Animal

  def method_1
    puts "hey, I am faithful"
  end

end

Dog.new.method_1 # => “hey, I am faithful”
Dog.my_method # => “Hi, I am a Animal”
Dog.method_2 # => “My dog’s name is spike”

Require

It reads the file from the file system, parses it, saves to the memory and runs it in a given place. What does it mean? Simply, even if you change the required file when the script is running, those changes won’t be applied – Ruby will use the file from memory, not from the file system.

require gives you access to many libraries and extensions built in Ruby as well as many more stuff written by other programmers.

require 'csv'

class Report

  def generate_report
    CSV.generate(
        write_headers: false
      ) do |csv|

      # some code is here

    end
  end
end

In the above example csv is the file to be used from the memory.

Load

In most cases we’ll use require, but there are some cases when our module changes frequently we may want to pick up those changes in classes that loads this module. load reads and parses files every time the file (in which load is called) is executed.

So it’s possible to load a library multiple times and also when using the load method we must specify the “.rb” extension of the library file name.

load test_module.rb

class Test

  def my_method

    # some code is here which can
    # make use of test_module.rb library

  end
end

7 Responses to “Difference between include, extend, require and load in ruby

Leave a Reply

Your email address will not be published. Required fields are marked *