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
