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

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this link! 🙏

Thank you for your time!

the load method

The Kernel#load method loads and executes the file passed as parameter.

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 with the Kernel#require method is that a file can be loaded more than one time when using the load method.

In effect, 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 to the following example

$> tree

.

├── counter.rb 0 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, the $counter global variable is incremented at each call of load 'counter.rb' .

Voilà !

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com