如何在Ruby中获取当前工作目录的绝对路径?

发布于 2024-08-15 17:05:44 字数 214 浏览 8 评论 0原文

我在 Windows 上运行 Ruby,但我不知道这是否会产生影响。我想做的就是获取当前工作目录的绝对路径。 irb 可以做到这一点吗?显然,从脚本中可以使用 File.expand_path(__FILE__)

但从 irb 中我尝试了以下操作并收到了“权限被拒绝”错误:

File.new(Dir.new(".").path).expand

I'm running Ruby on Windows though I don't know if that should make a difference. All I want to do is get the current working directory's absolute path. Is this possible from irb? Apparently from a script it's possible using File.expand_path(__FILE__)

But from irb I tried the following and got a "Permission denied" error:

File.new(Dir.new(".").path).expand

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

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

发布评论

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

评论(7

枯叶蝶 2024-08-22 17:05:44

Dir.pwd is the current working directory

http://ruby-doc.org/core/Dir.html#method-c-pwd

无法言说的痛 2024-08-22 17:05:44

File.expand_path File.dirname(__FILE__) 将返回与调用此命令的文件相关的目录。

但是 Dir.pwd 返回工作目录(结果与在终端中执行 pwd 相同)

File.expand_path File.dirname(__FILE__) will return the directory relative to the file this command is called from.

But Dir.pwd returns the working directory (results identical to executing pwd in your terminal)

眼角的笑意。 2024-08-22 17:05:44

至于相对于当前执行脚本的路径,从Ruby 2.0开始你也可以使用

__dir__

所以这基本上是一样的

File.dirname(__FILE__)

As for the path relative to the current executing script, since Ruby 2.0 you can also use

__dir__

So this is basically the same as

File.dirname(__FILE__)
匿名的好友 2024-08-22 17:05:44

这将为您提供当前文件的工作目录。

File.dirname(__FILE__)

示例:

current_file:“/Users/nemrow/SITM/folder1/folder2/amazon.rb”

结果:“/Users/nemrow/SITM/folder1/folder2”

This will give you the working directory of the current file.

File.dirname(__FILE__)

Example:

current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"

result: "/Users/nemrow/SITM/folder1/folder2"

╄→承喏 2024-08-22 17:05:44

通过此您可以获得位于任何目录中的任何文件的绝对路径。

File.join(Dir.pwd,'some-dir','some-file-name')

这将返回

=> "/User/abc/xyz/some-dir/some-file-name"

Through this you can get absolute path of any file located in any directory.

File.join(Dir.pwd,'some-dir','some-file-name')

This will return

=> "/User/abc/xyz/some-dir/some-file-name"
じ违心 2024-08-22 17:05:44

如果想获取当前rb文件所在目录的完整路径:

File.expand_path('../', __FILE__)

If you want to get the full path of the directory of the current rb file:

File.expand_path('../', __FILE__)
黯淡〆 2024-08-22 17:05:44

如果您不打算在 Windows 或 *nix 以外的任何操作系统上运行代码。

`pwd`.chop

If you don't plan on running your code on Windows or anything other than *nix.

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