Forem

Pavs
Pavs

Posted on

1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay