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?
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('/').
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With