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 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 lowernumbered tiers:

  1. File objects to read and write the contents of files, and Dir objects 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.

  2. Class methods of File to manipulate files without opening them. For instance, to delete a file, examine its metadata, or change its permissions. ...

Get Ruby Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.