class Pathname

A Pathname object stores a string:

pn = Pathname('README.md') # => #<Pathname:README.md>
pn.to_s                    # => "README.md"

The string is usually an actual or potential path to an entry in the filesystem:

Pathname('lib')            # =>  #<Pathname:lib>        # Relative path.
Pathname('/usr/lib')       # => #<Pathname:/usr/lib>    # Absolute path.
Pathname('nosuch/foo')     # => #<Pathname:nosuch/foo>  # Need not exist.
Pathname('!@#$%^&*()')     # => #<Pathname:!@#$%^&*()>  # Need not be a valid path.

Through its many instance methods, the pathname object provides a consistent and convenient interface to numerous methods in other classes and modules:

Advantages of using a pathname instead of these others:

Without pathnames:

filepath = 'README.md'
File.exist?(filepath)    # => true
File.file?(filepath)     # => true
File.writable?(filepath) # => true
dirpath = 'tempdir'
Dir.mkdir(dirpath)
Dir.rmdir(dirpath)

With pathnames:

pn = Pathname('README.md')
pn.exist?    # => true
pn.file?     # => true
pn.writable? # => true
pn = Pathname('tempdir')
pn.mkdir
pn.rmdir

In addition to its wrapper methods, Pathname has certain “core” methods that are not simple wrappers:

Of particular interest may be cleanpath, which reduces a “noisy” path to a simpler form.

Some pathname methods return pathnames, which may be chained:

Pathname("/usr")
  .join("local")
  .join("bin")
  .exist?
# => true

A Pathname object is immutable (except for method freeze).

About the Examples

Many examples here use these variables:

# English text with newlines.
text = <<~EOT
  First line
  Second line

  Fourth line
  Fifth line
EOT

# Japanese text.
japanese = 'こんにちは'

# Binary data.
data = "\u9990\u9991\u9992\u9993\u9994"

# Text file.
File.write('t.txt', text)

# File with Japanese text.
File.write('t.ja', japanese)

# File with binary data.
f = File.new('t.dat', 'wb:UTF-16')
f.write(data)
f.close

What’s Here

First, what’s elsewhere. Class Pathname:

Here, class Pathname provides methods that are useful for:

Creating

Querying

Comparing

Analyzing

Converting

Ownership and Permissions

Reading and Writing

Times

Iterating

Other