Ruby中require、load、autoload的区别_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Ruby中require、load、autoload的区别

Ruby中require、load、autoload的区别

 2013/7/29 23:09:31  lanrion  程序员俱乐部  我要评论(0)
  • 摘要:require:require(filename)->trueorfalseRubytriestoloadthelibrarynamedstring,returningtrueifsuccessful.Ifthefilenamedoesnotresolvetoanabsolutepath,itwillbesearchedforinthedirectorieslistedin$:.Ifthefilehastheextension``.rb’’,itisloadedasasourcefile
  • 标签:Ruby 区别
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将会被加载。即理解为:第一使用时才会加载该文件,可以理解为懒加载。

?

发表评论
用户名: 匿名