问题描述
在我的Ruby程序中,我试图延迟加载一个库(破解
a>为好奇)。如果我这样做:
require'rubygems'
require'crack'
一切正常。然而,当我尝试这样做时:
require'rubygems'
autoload:破解'crack'
引发LoadError。 ( no file to load - crack )
为什么会引发此错误?是否因为'crack'(因此我的其他用户安装的宝石)不在我的$ LOAD_PATH中?
edit:
此外, autoload
可以与标准库一起使用:
autoload:Yaml,'yaml'
正常工作,没有错误。
您需要将'crack'gem添加到$ LOAD_PATH中:
gem'crack'
这是必要的,因为RubyGems将Kernel#require替换为尝试在必要时激活gem的方法,但在内核#load和autoload调用在后端加载时不会执行相同的操作。
In my Ruby program, I'm trying to lazy-load a library (crack for the curious).
If I do this:
require 'rubygems'
require 'crack'
Everything is working fine. However, when I try this:
require 'rubygems'
autoload :Crack, 'crack'
A LoadError is raised. (no such file to load -- crack)
Why is this error being raised? Is it because 'crack' (and therefore my other user-installed gems) are not in my $LOAD_PATH?
edit:
Furthermore, autoload
does work with the Standard Library:
autoload :Yaml, 'yaml'
works fine, and raises no errors.
You'll need to add the 'crack' gem to your $LOAD_PATH by doing:
gem 'crack'
This is necessary because RubyGems replaces Kernel#require with a method that attempts to "activate" the gem before requiring it if necessary, but doesn't do the same thing for Kernel#load - and autoload calls load on the backend.
这篇关于`autoload`会产生错误,但'require'不会(ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!