Chris Mendez in For Developers, Ruby

Ruby: Pathmap

The Ruby library Rake has an awesome tool called Filelist that is great for manipulating files. For example, suppose you had an array of files with different path names, using the pathmap method, you can do some elegant file path parsing without the need for regular expressions.

require 'rake'

list = FileList['file1.txt', 'file2.pdf', 'sources/file3.txt', 'bin/file4']

# Example 1
puts list.pathmap('%p')  
# Example 2
puts list.pathmap('%f')  
# Example 3
puts list.pathmap('%n')  
# Example 4
puts list.pathmap('%d')  
# Example 5
puts list.pathmap('%x')  
# Example 6
puts list.pathmap('%X')  
# Example 7
puts list.pathmap('%s')  

Example 1: %p This is the complete path.

["file1.txt", "file2.pdf", "sources/file3.txt", "bin/file4"]

Example 2: %f This is the base file name of the path with its extension, but without any directories.

["file1.txt", "file2.pdf", "file3. txt", "file4"]

Example 3: %n This is the file name of the path without its file extension.

["file1", "file2", "file3", "file4"]

Example 4: %d This is the directory list of the path.

[".", ".", "sources", "bin"] 

Example 5: %x This is the file extension of the path. It is an empty string if there is no extension.

[".txt", ".pdf", ".txt", ""]

Example 6: %X This includes everything but the file extension.

["file1", "file2", "sources/file3", "bin/file4"]


Suppose you have a file with an extension of .txt and you easily want to swap it out to .out. Here's how.

# Swap .txt with .out
path = FileList["/path/to/file.txt"].pathmap('%X.out').first  
puts path # => "/path/to/file.out"