是否有较短的方法要求在ruby的同一目录中有文件? [英] Is there a shorter way to require a file in the same directory in ruby?
问题描述
是否有较短的方法要求文件位于与执行脚本相同的目录中?
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
的原因:如果每次使用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
.
这篇关于是否有较短的方法要求在ruby的同一目录中有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!