Chapter 6. Files and Directories
As programming languages increase in power, we programmers get further and further from the details of the underlying machine language. When it comes to the operating system, though, even the most modern programming languages live on a level of abstraction that looks a lot like the C and Unix libraries that have been around for decades.
We covered this kind of situation in Chapter 3 with Ruby’s
Time objects, but the issue really shows up when
you start to work with files. Ruby provides an elegant object-oriented
interface that lets you do basic file access, but the more advanced file
libraries tend to look like the C libraries they’re based on. To lock a
file, change its Unix permissions, or read its metadata, you’ll need to
remember method names like
the meaning of obscure constants like
0644. This chapter will show you how to use the
simple interfaces, and how to make the more obscure interfaces easier to
Looking at Ruby’s support for file and directory operations, you’ll see four distinct tiers of support. The most common operations tend to show up on the lowernumbered tiers:
Fileobjects to read and write the contents of files, and
Dirobjects to list the contents of directories. For examples, see Recipes 6.5, 6.7, and 6.17. Also see Recipe 6.13 for a Ruby-idiomatic approach.
Class methods of
Fileto manipulate files without opening them. For instance, to delete a file, examine its metadata, or change its permissions. ...