红宝石:如何相对于另一个路径计算?(Ruby: How to calculate a path re

2019-07-30 10:32发布

比方说,我知道,我从开始的绝对路径,我想获得的绝对路径:

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

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

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

我怎样才能做到这样的事情在Ruby中?

Answer 1:

使用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


文章来源: Ruby: How to calculate a path relative to another one?