Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Pathname#relative_path_from

(::Pathname | ::string base_directory) -> ::Pathname
relative_path_from(source) → new_pathname

Returns a pathname containing the relative filesystem path from the given source to the path in self; source must be a directory path or a pathname containing a directory path:

Example
Pathname('.').relative_path_from('doc/language')   # => #<Pathname:../..>
Pathname('doc/language').relative_path_from('.')   # => #<Pathname:doc/language>
Pathname('doc').relative_path_from('doc/language') # => #<Pathname:..>

The paths need not exist:

Example
Pathname('nosuch').relative_path_from('nosuch/foo/bar/baz')
# => #<Pathname:../../..>

The two paths must be either both absolute or both relative:

Example
Pathname('/var').relative_path_from('/etc') # => #<Pathname:../var>
Pathname('/var').relative_path_from('doc')  # Raises ArgumentError
Pathname('doc').relative_path_from('/etc')  # Raises ArgumentError

Raises an exception if there is no such relative path:

Example
Pathname('foo').relative_path_from('..')    # Raises ArgumentError
See also #relative? #rename #realpath #rmdir also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0