Skip to content
class method

File.expand_path

(::string | ::_ToPath file_name, ?::string | ::_ToPath dir_string) -> ::String
File.expand_path(file_name [, dir_string] ) → abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~user” expands to the named user’s home directory.

Example
File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"

A simple example of using dir_string is as follows.

Example
File.expand_path("ruby", "/usr/bin")      #=> "/usr/bin/ruby"

A more complex example which also resolves parent directory is as follows. Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.

Example
File.expand_path("../../lib/mygem.rb", __FILE__)
#=> ".../path/to/project/lib/mygem.rb"

So first it resolves the parent of __FILE__, that is bin/, then go to the parent, the root of the project and appends lib/mygem.rb.

See also .exist? .extname .executable_real? .file? also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0