How Powerful Pathname Is #
How powerful Pathname is! Unfortunately I did not know. Have you ever been
annoyed which class to use, File, FileTest, Dir or Find? Use Pathname, instead.
That’s all (on UNIX platforms). The Pathname class, included in the Ruby 1.8
standard libraries, represents paths of directories and files, and is a facade
to File, FileTest, Dir and Find.
You can see some examples in the header lines of the source:
require 'pathname'
p = Pathname.new("/usr/bin/ruby")
size = p.size # 27662
isdir = p.directory? # false
dir = p.dirname # Pathname:/usr/bin
base = p.basename # Pathname:ruby
dir, base = p.split # [Pathname:/usr/bin, Pathname:ruby]
data = p.read
p.open { |f| _ }
p.each_line { |line| _ }
That means
p = "/usr/bin/ruby"
size = File.size(p) # 27662
isdir = File.directory?(p) # false
dir = File.dirname(p) # "/usr/bin"
base = File.basename(p) # "ruby"
dir, base = File.split(p) # ["/usr/bin", "ruby"]
data = File.read(p)
File.open(p) { |f| _ }
File.foreach(p) { |line| _ }
Pathname has exist?, file?, mkdir, rmdir, rmtree, children, find and so on as well.


netghost
I really love Pathname. It makes working with files quite easy. It does have a few occasional oddities with Windows, but that’s understandable ;)
Daniel Berger
I believe my feelings on this subject are well known.
As for Windows, netghost, I have a package called win32-pathname checked into CVS at http://www.rubyforge.org/projects/win32utils.
Nikolai Weibull
Wow! Thanks for pointing out this gem for me. I’m definitely going to be requring ‘pathname’ in the future.
rkb
It’s really nice. The only things I come across with that it doesn’t do is copying files (understandable, you need 2 files) and recursively deleting a directory: for that
FileUtils.rm_rfis still needed.But indeed, definitely candidate for ‘most useful ruby lib’.
Daniel Berger
And so, pathname2 was unleashed upon the world…
Comments are closed for this entry.