Ruby’s Pathname API

Share this article

Pathname docs

Ruby’s standard library is a treasure trove of useful classes, and the Pathname class is certainly one of them. Introduced in Ruby 1.9, Pathname represents a path on the file system, providing convenient access to functionality that is otherwise scattered across a handful of other classes like File, FileTest, and Dir.

Now that the life of Ruby 1.8 has officially come to an end, and 1.9 is nearing its fifth birthday, it’s high time to drop the legacy support and embrace the elegance and ease of use Pathname has to offer.

To show why Pathname was a much needed addition, let’s consider the more traditional way of manipulating path information. This is how we did things in the 1.8 days:

CONFIG_PATH = File.join(File.dirname(__FILE__), '..', 'config.yml')

Notice the use of class methods, a rare sight in a language where everything is an object. But what’s the alternative? The object-oriented thing-to-do would be to move the functionality closer to the data on which it operates. In this case, we’re simply manipulating strings, but it doesn’t really make sense to add join and dirname to String. A string is a far too generic a data type for such specific functionality.

Enter Pathname:

CONFIG_PATH = Pathname.new(__FILE__).dirname.join('..', 'config.yml')

By wrapping the string in a Pathname object, we get a clean API for manipulating the path. This code already looks a lot more like idiomatic Ruby. An important difference from Ruby’s vanilla strings is that Pathname instances are immutable. There are no methods that change the Pathname instance itself. Instead, all methods like dirname, join or basename return a new Pathname instance, leaving the existing instance unchanged.

The Pathname API

Methods on Pathname fall roughly into one of two categories: Either they simply manipulate the path string without accessing the file system, or they call out to the operating system to perform checks and operations on the file or directory itself. For the full list of eighty-something methods, you can check out the official Pathname API documentation. It’s worth noting that the docs are also available from a terminal through ri Pathname, or in irb with help 'Pathname'.

Let’s look at some methods you might find useful.

File Type and Permission Checks

pn = Pathname.new('/usr/bin/ruby')
pn.file?       # => true
pn.directory?  # => false

pn.absolute?   # => true
pn.relative?   # => false

pn.executable? # => true
pn.readable?   # => true
pn.writable?   # => false

pn.root?       # => false

Most of these correspond with methods on FileTest

File System Navigation and Querying

pn = Pathname.getwd # current working directory
pn.children   # => [ #<Pathname...>, ... ]
pn.each_child {|ch| ... }
pn = pn.parent

Pathname.glob('**/*.rb') # like Dir['**/*.rb'] but returns Pathnames

Pathname Manipulation

pn = Pathname.new('lib/mylib/awesome.rb')
pn.dirname                   # => #<Pathname:lib/mylib>
pn.basename                  # => #<Pathname:awesome.rb>
pn.extname                   # => ".rb"
pn.expand_path('/home/arne') # => #<Pathname:/home/arne/lib/mylib/awesome.rb>

Working with the Actual File

pn = Pathname.new(ENV['HOME']).join('.bashrc')
pn.size
pn.read
pn.open {|io| ... }
pn.each_line {|line| ... }
pn.rename('/tmp/foo')
pn.delete

Pathname() and to_path

There are two ways to create Pathname instances: through explicit construction as above, or through the Pathname() conversion method. While capitalized identifiers are typically reserved for classes and constants, Ruby has a number of built-in methods for converting arbitrary values to a specific type, named after the classes they convert to.

Array(1)                  # => [1]
Array(nil)                # => []
Array([1,2])              # => [1,2]
String(7)                 # => "7"
URI("http://example.com") # => #<URI::HTTP:0x1c0e URL:http://example.com>

These go hand in hand with a number of conversion hooks that objects can implement, like to_ary or to_str. Likewise, objects can implement to_path to indicate how they can be converted to a pathname. The pathname constructor is implemented in C for efficiency, but it would roughly translate to Ruby like this:

class Pathname
  def initialize(path)
    path = path.to_path if path.respond_to? :to_path
    @path = String(path)
  end
end

Say you are writing some scripts to help you manage your music collection. An AudioFile might look like this:

class AudioFile
  def initialize(path)
    @path = path
  end

  def to_path
    @path
  end

  # ...
end

Many built-in methods will wrap their file name arguments in a call to Pathname(), so you can pass in your AudioFile instance just the same.

af = AudioFile.new('...')
File.open(af) do |io|
  #...
end

When writing library code, reuse this pattern for maximum flexibility:

def read_configuration(config_file)
  parse_configuration(Pathname(config_file).read)
end

Now the caller of this code can pass in as config_file

  • a string
  • a Pathname
  • an object that responds to to_path
  • any object that can be converted with String()

Building a Music Collection Browser

To show how powerful and intuitive working with Pathname is, we’ll write a little API for browsing our music collection. The files are organized with songs grouped in directories per album, which are again grouped per artist. For example: ~/Music/Arsenal/Oyebo Soul/09_How Come.flacc.

We’re aiming for an easy to use API that looks like this:

mc = MusicCollection.new('~/Music') # => #<MusicCollection 'Music'>
mc.artists.first                    # => #<Artist 'Arsenal'>
mc.artists.first.albums.first       # => #<Album 'Oyebo Soul'>
mc.songs.count                      # => 120
mc.songs.first.path                 # => #<Pathname: ...>
mc.songs.first.play

The Song class is essentially our AudioFile class from above:

class Song
  attr_reader :path
  alias to_path path

  def initialize(path)
    @path = Pathname(path).expand_path
  end

  def name
    String(path.basename(path.extname))
  end

  def play(options = {})
    exec(options.fetch(:player, 'mplayer'), String(path))
    # OS X users can use player: '/usr/bin/afplay'
  end
end

We immediately call expand_path to normalize our input. This will expand ~ into the user’s home directory, and will resolve any relative file names (like . and ..). This way, we are sure to have an absolute file name.

Now we need to add classes for Album, Artist, and, finally, the MusicCollection itself. Since all of these are wrapper classes around a Pathname, we can pull the common plumbing into a base class.

class PathnameWrapper
  attr_reader :path
  alias to_path path

  def initialize(path)
    @path = Pathname(path).expand_path
  end

  def name
    # ...
  end

  def to_s
    # ...
  end
end

class Song < PathnameWrapper
  def play
    # ...
  end
end

Now we can add an Album and provide navigation methods back and forth. We will also add files and directories helpers to our base class, along with a to_proc class method. When passing in an object as a block with &, Ruby will use to_proc to find an implementation for the block. This way we get shorthand for typecasting all elements of a collection.

class PathnameWrapper
  # ...

  def directories
    path.children.select(&:directory?)
  end

  def files
    path.children.select(&:file?)
  end

  def self.to_proc
    ->(path) { new(path) }
  end
end

class Album < PathnameWrapper
  EXTENSIONS = %w[.flacc .m4a .mp3 .ogg .wav]

  def songs
    files.select do |file|
      EXTENSIONS.any? {|ext| ext == file.extname }
    end.map(&Song)
  end
end

class Song < PathnameWrapper
  # ...

  def album
    Album.new(path.dirname)
  end
end

To wrap things up we introduce Artist and MusicCollection.

class MusicCollection < PathnameWrapper
  def artists
    directories.map(&Artist)
  end

  def albums
    artists.flat_map(&:albums)
  end

  def songs
    albums.flat_map(&:songs)
  end
end

class Artist < PathnameWrapper
  def albums
    directories.map(&Album)
  end
end

class Album < PathnameWrapper
  # ...

  def artist
    Artist.new(path.dirname)
  end
end

class Song < PathnameWrapper
  # ...

  def artist
    album.artist
  end
end

Now we can browse back and forth between songs, albums, and artists.

This concludes the basics of our MusicCollection API, as well as our introduction to the Pathname class. Having a good grasp on Ruby’s standard library can help to make your code more elegant, correct, and concise. Here we’ve zoomed in on a single small component, highlighting its many uses. Go forward and use Pathname wisely.

Frequently Asked Questions (FAQs) about Ruby’s Pathname API

What is the primary function of Ruby’s Pathname API?

Ruby’s Pathname API is a powerful tool that allows you to manipulate file paths in a clean and object-oriented manner. It provides a set of methods to parse and manipulate file paths. It’s a more intuitive and less error-prone alternative to using strings to handle file paths. With Pathname, you can easily perform operations like joining paths, finding relative paths, and checking if a path is absolute or relative.

How do I create a new Pathname object?

Creating a new Pathname object is straightforward. You simply call the Pathname.new method and pass the path as a string. For example, Pathname.new("/home/user/documents") creates a new Pathname object for the “/home/user/documents” directory.

How can I join two paths using Pathname?

Joining two paths using Pathname is easy and intuitive. You can use the #join method, which returns a new Pathname object. For example, if you have two paths, “/home/user” and “documents”, you can join them like this: Pathname.new("/home/user").join("documents").

How can I check if a path is absolute using Pathname?

You can use the #absolute? method to check if a path is absolute. This method returns true if the path is absolute, and false otherwise. For example, Pathname.new("/home/user/documents").absolute? will return true.

How can I find the relative path between two paths using Pathname?

You can use the #relative_path_from method to find the relative path from one path to another. This method takes another Pathname object as an argument and returns a new Pathname object representing the relative path. For example, Pathname.new("/home/user/documents").relative_path_from(Pathname.new("/home/user")) will return “documents”.

How can I check if a file or directory exists at a certain path using Pathname?

You can use the #exist? method to check if a file or directory exists at the path represented by the Pathname object. This method returns true if the file or directory exists, and false otherwise. For example, Pathname.new("/home/user/documents").exist? will return true if the “/home/user/documents” directory exists.

How can I read the contents of a file using Pathname?

You can use the #read method to read the contents of a file. This method returns a string containing the contents of the file. For example, Pathname.new("/home/user/documents/my_file.txt").read will return the contents of the “my_file.txt” file.

How can I write to a file using Pathname?

You can use the #write method to write to a file. This method takes a string as an argument and writes it to the file. For example, Pathname.new("/home/user/documents/my_file.txt").write("Hello, world!") will write “Hello, world!” to the “my_file.txt” file.

How can I get the parent directory of a path using Pathname?

You can use the #parent method to get the parent directory of a path. This method returns a new Pathname object representing the parent directory. For example, Pathname.new("/home/user/documents").parent will return “/home/user”.

How can I get the last component of a path using Pathname?

You can use the #basename method to get the last component of a path. This method returns a new Pathname object representing the last component. For example, Pathname.new("/home/user/documents").basename will return “documents”.

Arne BrasseurArne Brasseur
View Author

Arne is a developer, public speaker, programming coach, author and open-source contributor. With a passion for both human and programming languages, he has spent the last decade teaching and exploring the finer points of Ruby, LISP, Haskell, Mandarin Chinese, and others. When not hopping conferences or Pacific islands, he can be found at his home base in Berlin, brewing fine teas while pondering the future of open-source and the web.

Share this article
Read Next
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form