Reading from a File

Once we’ve opened a file, the next step is to read its contents. We’ll start with the simplest way to do this—reading the whole file into a string, allowing us to perform many kinds of processing with the text contained in the file. We’ll then look at how we can break the file’s content up into lines and loop through them, a task that’s frequently necessary when processing log files, when processing text written by people, and in many other situations.

Reading a Whole File at Once

The easiest way to access the contents of a file in Ruby is to read the entire file in one go. It’s not always the right solution, especially when working with bigger files, but it makes sense in many cases.

We can achieve this by using the read ...

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.