struct Path
- Path
- Struct
- Value
- Object
Overview
A Path
represents a filesystem path and allows path-handling operations
such as querying its components as well as semantic manipulations.
A path is hierarchical and composed of a sequence of directory and file name
elements separated by a special separator or delimiter. A root component,
that identifies a file system hierarchy, may also be present.
The name element that is farthest from the root of the directory hierarchy is
the name of a file or directory. The other name elements are directory names.
A Path
can represent a root, a root and a sequence of names, or simply one or
more name elements.
A Path
is considered to be an empty path if it consists solely of one name
element that is empty or equal to "."
. Accessing a file using an empty path
is equivalent to accessing the default directory of the process.
Examples
Path["foo/bar/baz.cr"].parent # => Path["foo/bar"]
Path["foo/bar/baz.cr"].basename # => "baz.cr"
Path["./foo/../bar"].normalize # => Path["bar"]
Path["~/bin"].expand(home: true) # => Path["/home/crystal/bin"]
For now, its methods are purely lexical, there is no direct filesystem access.
Path handling comes in different kinds depending on operating system:
Path.posix()
creates a new POSIX pathPath.windows()
creates a new Windows pathPath.new()
meansPath.posix
on POSIX platforms andPath.windows()
on Windows platforms.
# On POSIX system:
Path.new("foo", "bar", "baz.cr") == Path.posix("foo/bar/baz.cr")
# On Windows system:
Path.new("foo", "bar", "baz.cr") == Path.windows("foo\\bar\\baz.cr")
The main differences between Windows and POSIX paths:
- POSIX paths use forward slash (
/
) as only path separator, Windows paths use backslash (\
) as default separator but also recognize forward slashes. - POSIX paths are generally case-sensitive, Windows paths case-insensitive
(see
#<=>
). - A POSIX path is absolute if it begins with a forward slash (
/
). A Windows path is absolute if it starts with a drive letter and root (C:\
).
Path.posix("/foo/./bar").normalize # => Path.posix("/foo/bar")
Path.windows("/foo/./bar").normalize # => Path.windows("\\foo\\bar")
Path.posix("/foo").absolute? # => true
Path.windows("/foo").absolute? # => false
Path.posix("foo") == Path.posix("FOO") # => false
Path.windows("foo") == Path.windows("FOO") # => true
Included Modules
- Comparable(Path)