When to use "load" rather than "require" in Ruby?

778 Views Asked by At

I understand that require loads the file only once, while load loads it every time it is called.

It looks like using require is preferable in most situations.

My question is, when would I use load rather than require ?

3

There are 3 best solutions below

0
On BEST ANSWER

If you need to force something to reload (a common example would be a web server or a test server). You should use autoload when there is a reasonable chance some piece of code won't get hit, or you want to address app load time issues. You should use require at all other times.

1
On

Load takes in a file's full name path such as:

load "/path/to/file.rb"

Meanwhile, require will load the file only once AND does not require you to specify the .rb extension:

require "/path/to/file"
require "/path/to/file.rb"

It's recommended that you use require in practice for better performance but I've read that Rails uses load during development mode so you do not have to restart the server on every change.

0
On

Well I think the answer is in your question. You wrote:

"that require loads the file only once"

So now what happens if you change the file or something external changes the file? With load you get the "state" which holds during the load. With require not.