问题描述
有没有办法重新加载"或刷新"内存中的 rubygem?当我在 irb 中玩游戏时,偶尔我喜欢修改我的 gem 文件,如果我需要相同的 gem,它不会更新到内存中并给出false"输出.目前我必须退出 IRB,重新进入 IRB,然后再次需要 gem,必须有更好的方法......它是什么?
Is there a way to "reload" or "refresh" a rubygem in memory? As i'm playing in irb, occasionally I like to modify my gem files, and if i require the same gem, it does not update into memory and gives the output "false". Currently I have to exit IRB, get back into IRB and then require the gem again, there has to be a better way...what is it?
推荐答案
正如其他人所建议的,您可以使用 Kernel#load.但是,不要浪费时间查找和加载每个 gem 文件,因为所有需要的文件都存储在 $" 中.有了这些知识,这里有一个重新加载 irb 命令:
As others have suggested, you can use Kernel#load. However, don't waste your time finding and loading each gem file as all files that have been required are stored in $". Armed with this knowledge, here's a reload irb command:
def reload(require_regex)
$".grep(/^#{require_regex}/).each {|e| load(e) }
end
例如,如果您在 irb 中使用 hirb gem,您只需重新加载:
For example, if you were using the hirb gem in irb, you would simply reload with:
>> reload 'hirb'
如果由于某种原因加载不起作用(它对文件扩展名比 require 更挑剔),您可以通过首先删除它在 $" 中的条目来重新请求任何文件.有了这个建议,上面的命令将是:
If for whatever reason load doesn't work (it is pickier about file extensions than require is), you can re-require any file by first deleting its entry in $". With this advice the above command would be:
def reload(require_regex)
$".grep(/^#{require_regex}/).each {|e| $".delete(e) && require(e) }
end
选择适合您的那个.就我个人而言,我使用后者.
Pick whichever works for you. Personally, I use the latter.
这篇关于在 IRB 中重新加载 rubygem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!