Ruby 脚本可以告诉它位于哪个目录吗?

发布于 2024-08-20 05:07:17 字数 157 浏览 3 评论 0原文

受到“获取 Bash 的源目录的启发来自内部的脚本”,Ruby 的方法是什么?

Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

水中月 2024-08-27 05:07:17

对于较新版本的 Ruby,请尝试:

  • __dir__

对于较旧版本的 Ruby (<2.0),可以使用以下命令找到正在运行的脚本:

  • File.dirname(__FILE__) -相对路径;或
  • File.expand_path(File.dirname(__FILE__)) - 绝对路径。

注意:即使在调用Dir.chdir之后,使用__dir__也会返回脚本路径;然而,使用旧语法可能不会返回脚本的路径。

For newer versions of Ruby, try:

  • __dir__

For older versions of Ruby (< 2.0), the script being run can be found using:

  • File.dirname(__FILE__) - relative path; or
  • File.expand_path(File.dirname(__FILE__)) - the absolute path.

Note: Using __dir__ will return the script path even after a call to Dir.chdir; whereas, using the older syntax may not return the path to the script.

々眼睛长脚气 2024-08-27 05:07:17

使用 __dir__

从 Ruby 2.0 开始,__dir__ 是获得此信息的最简单方法。它

返回文件目录的规范化绝对路径
从中调用此方法。

请参阅 __dir__ 文档,以及“为什么 __FILE__ 大写而 __dir__ 小写?” 。

Use __dir__

As of Ruby 2.0, __dir__ is the simplest way to get this. It

Returns the canonicalized absolute path of the directory of the file
from which this method is called.

See the __dir__ documentation, and "Why is __FILE__ uppercase and __dir__ lowercase?".

无妨# 2024-08-27 05:07:17

使用 __dir__

File.dirname(__FILE__) 不是获取存储脚本的目录的正确方法。

启动时工作目录和带有脚本文件的目录是相同的,但可能会改变。

例如:

Dir.chdir('..') do
    puts __dir__
    puts File.expand_path(File.dirname(__FILE__))
end

对于存储在 /Desktop/tmp 中的脚本文件,运行它将给出输出

/home/mateusz/Desktop/tmp
/home/mateusz/Desktop

use __dir__

File.dirname(__FILE__) is not a proper way to get directory where script is stored.

At start working directory and directory with script file is the same, but it may change.

For example:

Dir.chdir('..') do
    puts __dir__
    puts File.expand_path(File.dirname(__FILE__))
end

for script file stored in /Desktop/tmp running it will give output

/home/mateusz/Desktop/tmp
/home/mateusz/Desktop
ま柒月 2024-08-27 05:07:17

ENV["PWD"] 对我来说似乎是 Linux 下最简单的方法。我不知道与操作系统无关的方式。

ENV["PWD"] seems the simplest way for me under Linux. I don't know of an OS-agnostic way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文