liveBook · Manning

Pathname

As explained in The Well-Grounded Rubyist, Fourth Edition

Pathname is a Ruby standard library class that represents filesystem pathnames and provides operations for querying and manipulating paths.

Pathname is a Ruby standard-library class for representing filesystem paths as objects. Load it with require 'pathname', then create an object with Pathname.new(path_string). Its methods query and manipulate the path while preserving the Pathname abstraction instead of repeatedly converting between objects and strings. section 12.0 section 12.5.2

For a pathname such as /Users/dblack/hacking/test1.rb, Pathname provides focused operations:

  • basename returns the final path component as another Pathname; puts or to_s exposes its string representation. section 12.5.2
  • dirname returns the containing directory as a Pathname, while extname returns the final extension as a string such as ".rb". section 12.5.2
  • ascend yields the original path and each parent directory, truncating one rightmost segment at every step; ascend.to_a collects those Pathname objects. section 12.5.2
  • Many additional methods are proxied from File, Dir, IO, and other classes, but Pathname-specific operations emphasize knowledge a path can provide about itself. section 12.5.2

Walk upward through a path

require 'pathname' path = Pathname.new('/Users/dblack/hacking/test1.rb') path.ascend do |dir| puts "Ascended to #{dir.basename}" end # Ascended to test1.rb # Ascended to hacking # Ascended to dblack # Ascended to Users # Ascended to / Because dir remains a Pathname object on every iteration, basename can be called directly inside the block. section 12.5.2

>> require 'pathname'
=> true   # or 'false' if your irb has already loaded pathname
>> path = Pathname.new("/Users/dblack/hacking/test1.rb")
=> #<Pathname:/Users/dblack/hacking/test1.rb>

Start an IRB-sized Pathname example by loading the library and constructing a pathname object. section 12.5.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains construction, path queries, parent traversal, returned object types, and selected behavior while deferring proxied methods.
Examples
Uses an absolute Ruby source path to demonstrate basename, dirname, extname, ascend, block output, and array collection.
What it assumes
Assumes basic Ruby method calls and blocks while teaching library loading, Pathname construction, and object-returning path operations.
What you can do after
Apply it via Pathname to inspect path components and traverse parent directories without converting each result to a string.
How it connects
Connects Pathname with File, Dir, IO, FileUtils, StringIO, and standard-library file and I/O facilities.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.