开发者

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

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 situa开发者_JS百科tions.

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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜