发现 ruby require 方法会加载文件?
ruby 中的 require
方法将搜索 lib_path 并加载找到的第一个匹配文件(如果需要)。无论如何,是否可以打印要加载的文件的路径。我正在寻找类似于 bash 中的 which
命令的理想内置功能,并希望它也能这么简单。谢谢。
The require
method in ruby will search the lib_path and load the first matching files found if needed. Is there anyway to print the path to the file which would be loaded. I'm looking for, ideally built-in, functionality similar to the which
command in bash and hoping it can be that simple too. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道内置功能,但定义自己的功能并不难。这是改编自这个问题<的解决方案< /a>:
说明:
$:
是预定义变量。它是一个数组,用于搜索可以load
或require
的文件。which
方法遍历每个路径,查找您调用它的文件。如果找到匹配项,则返回文件路径。我假设您只希望输出为一行,显示所需文件的完整文件路径,例如
which
。如果您还想查看您的required
文件将自行加载的文件,则链接问题中的解决方案可能更合适:I don't know of a built-in functionality, but defining your own isn't hard. Here's a solution adapted from this question:
Explanation:
$:
is a pre-defined variable. It's an array of places to search for files you canload
orrequire
. Thewhich
method iterates through each path looking for the file you called it on. If it finds a match, it returns the file path.I'm assuming you just want the output to be a single line showing the full filepath of the
required
file, likewhich
. If you want to also see the files yourrequired
file will load itself, something like the solution in the linked question might be more appropriate:$ gem 其文件名 #(无 .rb 后缀)是我使用的...
$ gem which filename # (no .rb suffix) is what I use...