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#expand_path

(?::String dir) -> ::Pathname
expand_path(dirpath = '.') → new_pathname

Returns a new pathname containing the absolute path for self.

Evaluates a relative path with respect to the directory given by dirpath:

Example
Dir.chdir('/snap')
# Default dirpath.
Pathname('README').expand_path                  # => #<Pathname:/snap/README>
Pathname('bin').expand_path                     # => #<Pathname:/snap/bin>
Pathname('bin/../var').expand_path              # => #<Pathname:/snap/var>  # Cleaned.
# Other dirpath.
Pathname('../zip').expand_path('/usr/bin/ruby') # => #<Pathname:/usr/bin/zip>
Dir.chdir('/usr/bin')
Pathname('../../snap').expand_path(__FILE__)    # => #<Pathname:/usr/snap>

Evaluates an absolute path without respect to dirpath:

Example
Pathname('/snap').expand_path                       # => #<Pathname:/snap>
Pathname('/snap').expand_path.expand_path('nosuch') # => #<Pathname:/snap>
Pathname('/snap/../snap').expand_path               # => #<Pathname:/snap>  # Cleaned.

More examples:

Example
Dir.chdir('/usr/bin')
Pathname('../../snap').expand_path(__FILE__) # => #<Pathname:/usr/snap>
Pathname('../../snap').expand_path           # => #<Pathname:/snap>
See also #exist? #extname #executable_real? #file? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0