Ruby:如何计算相对于另一个的路径?

时间:2012-07-13 13:15:01

标签: ruby relative-path

让我说我知道我开始的绝对路径以及我想要达到的绝对路径:

first = '/first/path'
second = '/second/path'

现在我想弄清楚如何构建一个相对于第一个的路径。例如:

# answer should be /first/path/../../second/path
path = second.get_path_relative_to(first)

我如何在Ruby中做这类事情?

1 个答案:

答案 0 :(得分:58)

使用Pathname#relative_path_from

require 'pathname'

first = Pathname.new '/first/path'
second = Pathname.new '/second/path'

relative = second.relative_path_from first
# ../../second/path

first + relative
# /second/path