ruby中require和load的区别

今天在读rspec源代码的时候发现rspec会自动去load一些以_spec结尾的文件作为example 和 example group。

在这里顺便说一下ruby里loadrequire的区别。

  • load: 加载文件,比如load 'example.rb',不放重复加载
  • require: 加载文件,比如load 'example',只加载1次

代码说明: 新建2个文件。test.rb, file_to_be_load.rb

file_to_be_load.rb

puts 'It is in ' + __FILE__

test.rb

require 'file_to_be_load' # print It is in file_to_be_load.rb
require 'file_to_be_load' # print nothing
 
load 'file_to_be_load.rb' # print It is in file_to_be_load.rb
load 'file_to_be_load.rb' # print It is in file_to_be_load.rb again
原文地址:https://www.cnblogs.com/nbkhic/p/2237202.html