如何在Ruby中获取当前工作目录的绝对路径?
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Dir.pwd
是当前工作目录http: //ruby-doc.org/core/Dir.html#method-c-pwd
Dir.pwd
is the current working directoryhttp://ruby-doc.org/core/Dir.html#method-c-pwd
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 executingpwd
in your terminal)至于相对于当前执行脚本的路径,从Ruby 2.0开始你也可以使用
所以这基本上是一样的
As for the path relative to the current executing script, since Ruby 2.0 you can also use
So this is basically the same as
这将为您提供当前文件的工作目录。
示例:
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.
Example:
current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"
result: "/Users/nemrow/SITM/folder1/folder2"
通过此您可以获得位于任何目录中的任何文件的绝对路径。
这将返回
Through this you can get absolute path of any file located in any directory.
This will return
如果想获取当前rb文件所在目录的完整路径:
If you want to get the full path of the directory of the current rb file:
如果您不打算在 Windows 或 *nix 以外的任何操作系统上运行代码。
If you don't plan on running your code on Windows or anything other than *nix.