DEV Community


Posted on

Ruby chip cookie: Loading and Requiring

I was reading about namespaces in Ruby the other day and came across an interesting point where it compared require and load . 

Since I started writing Ruby, I did not though about the secrets behind the usage of require when other languages use load.

Let's suppose we have a file called weather_forecast.rb , that just has some functionality in it for returning weather forecasting information.
In order to execute it in our code, we could do something like load('weather_forecast.rb')

Everything looks good up to this point. We load the code, use it in our program, and move on with our lives. 

However, the constants that the file defined, are not removed once the file has loaded, and can pollute our program. 

To solve this problem, we could load the file as such load('weather_forecast.rb', true). The true argument, loads the file wrapping it around an anonymous namespace containing all constants that will be destroyed after the code is loaded.

On the other hand, we find require. It also loads code, but rather than loading it for execution, as load does, it imports the library avoiding those leftover class names. 

As an additional fact, require tries only once to load the file, while load does it every time the file is executed.

Discussion (0)