RubyCademy
Published in

RubyCademy

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

Before to start

RubyCademy.com is now live!

RubyCademy is a learning center for developers who are in their first or second professional experience such as

  • self-taught Rubyist
  • post-bootcamp dev
  • looking for your first job
  • young graduate
  • junior or mid-level dev

and who want to consolidate their knowledge of Ruby and Ruby on Rails.

So at RubyCademy, our content is designed to help you learn important notions in record time that you can directly apply on your day-to-day work.

Feel free to visit our website and subscribe to start your journey to become a better Rubyist! 💯👇😉

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à !

Thank you for taking the time to read this post :-)

Feel free to 👏 and share this Medium post if it has been useful for you.

Here is a link to my last medium post: Requiring a file or library in Ruby.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store