The difference between the requirement and the load for the "load" and "execution"

The following are some snippets of documentation for Kernel :

Kernel loading

Loads and executes the Ruby program in the file filename ...

Kernel # required

Loading name ...

I know that there are differences between require and load , for example:

  • require will be bound to the rb extension, and load will not
  • require save the ruby ​​file path inside $LOADED_FEATURES aka $" , but load will not
  • require will look for $LOADED_FEATURES before “uploading” the file again until load is

I am interested to know about the difference between the word “load” and the word “performs”.

The documentation seems to be two different things. For me, "load" will mean "Hey, I know about this file now," while "execute" will mean "Hey, I know about this file now, and I will also run all the commands."

But I do not think this is right.

For example, given the following structure:

 $ tree . ├── bar.rb ├── baz.rb └── foo.rb 0 directories, 3 files 

with foo.rb:

 $LOAD_PATH << __dir__ require 'bar' load 'baz.rb' 

bar.rb:

 puts "Inside of bar..." 

baz.rb:

 puts "Inside of baz..." 

When I ran foo.rb , I would expect "Inside of baz ..." to print, but not "Inside of bar ..." because load "loaded and executed", and require just "loaded". But what actually happens, both seem to be "doable":

 $ ruby foo.rb Inside of bar... Inside of baz... 

So is there any difference between “downloading” and “executing” a ruby ​​file?

+5
source share
1 answer

The file is always executed.

In Ruby, there is no such thing as downloading a file without executing it. All this expression in Ruby should be executed. Even class and def are simply statements.

To illustrate this here, a silly example

 class Mystery < [Array, Object, String, Fixnum].sample ... end 

This creates a class with a random superclass. To illustrate that Ruby has no declarations other than executable instructions.

So, there is no such thing as not executing a Ruby file. The difference between load and require is as you described, the latter keeps track of all downloaded files so as not to reload them.


PS and another example

 ruby --dump insns -e 'def example; end' == disasm: <RubyVM::InstructionSequence:<main>@-e>====================== 0000 trace 1 ( 1) 0002 putspecialobject 1 0004 putspecialobject 2 0006 putobject :example 0008 putiseq example 0010 opt_send_without_block <callinfo!mid:core#define_method, argc:3, ARGS_SIMPLE> 0012 leave == disasm: <RubyVM::InstructionSequence: example@-e >===================== 0000 trace 8 ( 1) 0002 putnil 0003 trace 16 ( 1) 0005 leave 

As you can see, def example; end def example; end is an operator and internally calls the define_method method. So def is just syntactic sugar for calling the method.

+7
source

Source: https://habr.com/ru/post/1262133/


All Articles