Ruby中require、load、autoload的区别

require:
require(filename) -> true or false
Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ``.rb’’, it is loaded as a source file; if the extension is ``.so’’, ``.o’’, or ``.dll’’, or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ``.rb’’, ``.so’’, and so on to the name. The name of the loaded feature is added to the array in $". A feature will not be loaded if its name already appears in $". The file name is converted to an absolute path, so ``require 'a'; require './a'’’ will not load a.rb twice.

个人翻译:

   Ruby 会尝试去根据require(filename)中的filename去加载库,如果加载成功即返回tru。如果filename不能解析成一个绝对路径,它会直接在$:.中查找。如果加载文件有“.rb”的扩展名,将会被加载成资源文件,如果是“.so”, ".o"或者是“.dll”,或者在当前平台下任何的可共享的库扩展名,Ruby都会将其当成Ruby的扩展资源进行加载。否则,Ruby会尝试将“.rb”,".so"等等拼接在filename。加载过后的文件特性将会被添加进$的数组中。如果在$数组中,某个特性的名字已经存在,将不会重复被加载。文件名也会被转换为绝对路径,所以``require 'a'; require './a'’’不会再第二次加载a.rb。

 

个人理解: require也就是只会加载一次,第一次加载成功则返回true,重复加载则会返回faluse。

 

load: 

load(filename, wrap=false) → true 写道
Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program’s global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

 个人翻译:加载并执行在文件里的Ruby程序。如果filename不能解析成一个绝对路径,它会直接在$:.中查找。 wrap是可选参数,默认为false,如果设为true,则这个文件将在匿名模块下运行,从而包括调用者的名字空间。任何filename里面的局部变量在装载它的环境下是不可用的。

 

个人理解:加载并执行,而且 load是每次都会重新加载。只要你的代码有修改,不用通过重启服务器也可以直接重新加载你修改过的内容。

 

autoload: 

autoload(module, filename) → nil 写道
Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

 个人翻译: 在第一次访问module(可能是字符串或者是符号)时,filename将会被加载。即理解为:第一使用时才会加载该文件,可以理解为懒加载。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值