When do you need to use `require`,` load` or `autoload` in Ruby?

I understand the subtle differences between require , load and autoload in Ruby, but my question is, how do you know which one to use?

Besides being able to wrap load in an anonymous module, require seems preferable.

But then autoload allows you lazy boot files - it sounds fantastic, but I'm not sure if you type more require

Is one method preferable to another? Is there a situation where one method stands out?

+48
ruby module
Apr 29 '09 at 21:12
source share
4 answers

Generally, you should use require . load will reload the code every time, so if you do this from several modules, you will do a lot of extra work. The laziness of autoload sounds nice in theory, but many Ruby modules do things like monkey-packing of other classes, which means that the behavior of the unrelated parts of your program may depend on whether the class was still used or not. autoload also deprecated , so it should be avoided.

If you want to create your own automatic rebooter that loads your code every time it changes, or every time someone clicks on a URL (for development purposes, so you don't have to restart the server every time) using load since it is reasonable.

+49
Apr 29 '09 at 23:08
source share
β€” -

mylibrary.rb

 puts "I was loaded!" class MyLibrary end 

Try it on irb

 irb(main):001:0> require 'mylibrary' I was loaded! => true irb(main):001:0> autoload :MyLibrary, 'mylibrary' => nil irb(main):002:0> MyLibrary.new I was loaded! => #<MyLibrary:0x0b1jef> 

See the difference.

+14
Dec 16 2018-11-12T00:
source share

here what you get with autoload over require :

autoload is autoload designed to speed up the initialization phase of your Ruby or Rails program. Without loading resources until they are needed, this can speed things up a bit.

Another advantage is that you may not need to download some parts of the code if the user does not use certain functions, thereby improving load times and reducing memory footprint.

+10
Oct 17 2018-11-11T00:
source share

Besides what others have already told you, the future of autoload uncertain. It was deprecated in Ruby 2.0, but deprecation was not done on time to freeze the 2.0 feature. autoload expected to become obsolete in Ruby 2.1, but this is no longer the case .

+5
Jun 14 '13 at 12:16
source share



All Articles