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

Andrew picture Andrew · Jul 13, 2012 · Viewed 10.4k times · Source

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?

Answer

Matheus Moreira picture Matheus Moreira · Jul 13, 2012

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