You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby中获取Dir对象所代表的绝对路径?

获取Ruby Dir对象的绝对路径(不受当前工作目录变化影响)

你之前用File.absolute_path(dir.path)失效的核心原因是:这个方法默认以当前工作目录为基准解析路径,一旦后续切换了工作目录,就会基于新目录解析原相对路径,自然得到错误结果。

下面是两种可靠的解决方法:

方法一:直接调用Dir对象的realpath方法

这是最简洁的方式,Dir#realpath会直接返回该Dir对象指向目录的绝对路径,完全不受当前工作目录变化的影响:

def get_dir_absolute_path(dir)
  dir.realpath
end

方法二:给File.absolute_path指定基准目录

利用File.absolute_path的第二个参数,把Dir对象传入作为基准目录,这样方法会基于Dir对象实例化时的目录来解析路径,而非当前工作目录:

def get_dir_absolute_path(dir)
  File.absolute_path(dir.path, dir)
end

示例验证

# 假设初始工作目录为 /home/user
dir = Dir.new("./documents") # 用相对路径实例化Dir对象
Dir.chdir("/tmp") # 切换工作目录到/tmp

# 错误方式:返回错误的路径 /tmp/documents
puts File.absolute_path(dir.path)

# 正确方式1:返回实际绝对路径 /home/user/documents
puts dir.realpath

# 正确方式2:返回实际绝对路径 /home/user/documents
puts File.absolute_path(dir.path, dir)

内容的提问来源于stack exchange,提问作者XiaohuWang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:15:28