Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 206
Andrew Avatar asked Jul 13 '12 13:07

Andrew


People also ask

How do you use the relative path in Ruby?

Or you can use expand_path to convert relative path to absolute. Or you can calculate relative path between two dirs. require 'pathname'; puts Pathname. new('/').

How do you convert an absolute path to a relative path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.

What is __ file __ in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.


1 Answers

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 
like image 151
Matheus Moreira Avatar answered Oct 07 '22 11:10

Matheus Moreira