Chapter 7. 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 4 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 mtime, and the meaning of obscure constants like File::LOCK_EX and 0644. This chapter will show you how to use the simple interfaces, and how to make the more obscure interfaces easier to use.
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 lower-numbered tiers:
-
Fileobjects to read and write the contents of files, andDirobjects to list the contents of directories—for examples, see Recipes 7.5, 7.7, and 7.17. Also see Recipe 7.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access