问题描述
是否有更短的方法来要求位于同一目录中的文件(与正在执行的脚本相同)?
Is there a shorter way to require a file located in the same directory (as the script being executed)?
require File.expand_path(File.dirname(__FILE__) + '/some_other_script')
我读到 require "my_script"
和 require "./my_script"
实际上会加载脚本两次(ruby 不会识别它实际上是同一个脚本), 这就是为什么推荐 File.expand_path
的原因:如果每次需要脚本时都使用它,那么它只会加载一次.
I read that require "my_script"
and require "./my_script"
will actually load the script twice (ruby will not recognize that it is actually the same script), and this is the reason why File.expand_path
is recommended: if it is used every time the script is required, then it will only be loaded once.
在我看来,像 Ruby 这样简洁的语言似乎没有更短的解决方案,这似乎很奇怪.例如,python 只是这样:
It seems weird to me that a concise language like Ruby does not seem to have a shorter solution. For example, python simply has this:
import .some_other_module_in_the_same_directory
我想我可以对 require
进行猴子补丁...但这太邪恶了!;-)
I guess I could monkey-patch require
... but that's just evil! ;-)
推荐答案
从 ruby 1.9 开始你可以使用 require_relative
.
Since ruby 1.9 you can use require_relative
.
查看最新文档 了解require_relative
或另一个版本的核心 API.
Check the latest doc for require_relative
or another version of the Core API.
这篇关于是否有更短的方法来要求 ruby 中同一目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!