Loading a file in Ruby
In this article, we’re going to describe the Kernel#load
method.
NB: feel free to have a look to my previous article if you’re unfamiliar with the notion of absolute and relative paths
the load method
The Kernel#load
method loads and executes the file passed as an argument.
As the Kernel#require
method, this method expects that the argument includes an absolute path.
Otherwise, the method tries to find the file by prepending it with each path included in the $LOAD_PATH
global variable — or with the current working directory path.
The main difference withKernel#require
is that a file can be loaded more than one time when using the load
method.
Indeed, the load
method doesn’t store the absolute path in the $LOADED_FEATURES
global array.
NB: feel free to have a look to my previous article if you’re unfamiliar with the
Kernel#require
method or the$LOADED_FEATURES
global array.
Let’s have a look at the following example
$> tree
.
├── counter.rb0 directories, 1 file
$> cat ./counter.rb
$counter += 1
Here, we implement an incremental counter by using the $counter
global variable.
So, let’s try to load counter.rb
within an irb
session
irb> $counter = 0
=> 0
irb> load 'counter.rb'
=> true
irb> $counter
=> 1
irb> load 'counter.rb'
=> true
irb> $counter
=> 2
irb> $LOADED_FEATURES.grep /counter.rb/
=> []
Here we pass the counter.rb
argument to load
. Then load
determines an absolute path based on the current working directory.
When the file is loaded, the determined absolute path isn’t added to the $LOADED_FEATURES
global array.
So $counter
is incremented at each call of load 'counter.rb'
.
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚