Skip to content

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

class method

File.expand_path

(::path file_name, ?::path dir_string) -> ::String
File.expand_path(path, dirpath = '.') → absolute_path

Returns the string absolute path for the given path.

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

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

Evaluates an absolute path without respect to dirpath:

Example
File.expand_path('/snap')           # => "/snap"
File.expand_path('/snap', 'nosuch') # => "/snap"
File.expand_path('/snap/../snap')   # => "/snap"  # Cleaned.

More examples:

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