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
pathname_builtin.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/pathname_builtin.rb, line 1102
def relative_path_from(base_directory)
base_directory = Pathname.new(base_directory) unless base_directory.is_a? Pathname
dest_directory = self.cleanpath.path
base_directory = base_directory.cleanpath.path
dest_prefix = dest_directory
dest_names = []
while r = chop_basename(dest_prefix)
dest_prefix, basename = r
dest_names.unshift basename if basename != '.'
end
base_prefix = base_directory
base_names = []
while r = chop_basename(base_prefix)
base_prefix, basename = r
base_names.unshift basename if basename != '.'
end
unless same_paths?(dest_prefix, base_prefix)
raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
end
while !dest_names.empty? &&
!base_names.empty? &&
same_paths?(dest_names.first, base_names.first)
dest_names.shift
base_names.shift
end
if base_names.include? '..'
raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
end
base_names.fill('..')
relpath_names = base_names + dest_names
if relpath_names.empty?
Pathname.new('.')
else
Pathname.new(File.join(*relpath_names))
end
end
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