Opening a File

Before we can do something with a file, we need to open it. This signals our intent to read from or write to the file, allowing Ruby to do the low-level that make that intention actually happen on the filesystem. Once it’s done those things, Ruby gives us a File object that we can use to manipulate the file.

Once we have this File object, we can do all sorts of things with it: read from the file, write to it, inspect its permissions, find out its path on the filesystem, check when it was last modified, and much more.

To open a file in Ruby, we use the open method of the File class, telling it the path to the file we’d like to open. We pass a block to the open method, in which we can do whatever we like with the file. Here’s an ...

Get Text Processing with Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.