Ruby - require vs load

Introduction

As well as require, you can use load to load external source-code files into your program.

For example, this code would seem to function identically to the preceding code:

load 'string_extensions.rb' 
puts "This is a test".vowels.join('-') 

load requires a full filename, including the .rb suffix, whereas require assumes the .rb suffix.

Put this in a.rb:

puts "Hello from a.rb" 

And put this in a file called b.rb:

require 'a' 
puts "Hello from b.rb" 
require 'a' 
puts "Hello again from b.rb" 

Run with ruby b.rb to get the result:

Hello from a.rb 
Hello from b.rb 
Hello again from b.rb 

Here, the a.rb file is included only once. It's included on line 1, and "Hello from a.rb" gets printed to the screen.

But then when it's included again on line 3 of b.rb, nothing occurs. In contrast, consider this code:

load 'a.rb' 
puts "Hello from b.rb" 
load 'a.rb' 
puts "Hello again from b.rb" 

Hello from a.rb 
Hello from b.rb 
Hello from a.rb 
Hello again from b.rb 

With load, the code is loaded and reprocessed as new each time you use the load method.

require processes external code only once.

Ruby programmers nearly always use require rather than load.

load are useful only if the code in the external file has changed or if it contains active code that will be executed immediately.

Related Topics