Friday, December 13, 2013

Ruby: load vs require, include vs extend

When it comes to including files within another file, there are two methods we can use, load and require.

Here is a table that gives the differences

loadrequire
file pathabsolute/relativeabsolute/relative
file extensionRequiredOptional
Can load a file multiple times YesNo

The file path and file extension rows are pretty straightforward. The most important difference is the third row, Can load a file multiple times. You can load a file multiple times by using method load, but for require, you can't. That's because The absolute path of the loaded file is added to $LOADED_FEATURES. Every time a new file is going to be required, ruby checks if there is already a same absolute path in $LOADED_FEATURES, and if there is, the file won't be loaded again.

It's easy for beginner to confuse load/require with include/extend. To some extent, these two groups of methods are similar. However, they are used under different context. include and extend are used to adding methods from a module to classes. If you include a module within a  class, all the methods within that module will be added to the class as its instance methods. If you extend a module within a  class, all the methods within that module will be added to the class as its class methods.  See the example below,

module Mod_1
  def hello1
    puts "Hello from Mod_1.\n"
  end
end

module Mod_2
  def hello2
    puts "Hello from Mod_2.\n"
  end
end

class Klass
  include Mod_1
  extend Mod_2
  def hello3
    puts "Hello from Klass.\n"
  end
end

a = Klass.new
a.hello1      
Hello from Mod_1
=> nil 
Klass.hello2
Hello from Mod_2
=> nil
a.hello3
Hello from Klass
=> nil

No comments:

Post a Comment