Ruby: How to calculate a path relative to another one?

青春壹個敷衍的年華 提交于 2019-12-03 08:08:44

问题


Let's say I know the absolute path that I am starting from and the absolute path that I am trying to get to:

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

Now I want to figure out how to construct a path that is relative to the first. For example:

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

How can I do this sort of thing in Ruby?


回答1:


Use 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


来源:https://stackoverflow.com/questions/11471261/ruby-how-to-calculate-a-path-relative-to-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!