Writing to Files

Compared to writing to other processes, writing to files is a relative breeze—there’s only a limited number of ways to do it. This isn’t really surprising, I suppose, but what’s interesting is typically the content—what’s actually being written—rather than the mechanism of writing.

In Chapter 1, Reading from Files, we looked at how we could use open to obtain a File object that enabled us to read from a file. It looked like this:

 
File.open(​"file.txt"​) ​do​ |file|
 
contents = file.read
 
end

What if, rather than using read to read from the file, we tried to use write or puts to write to it—something like this?

 
File.open(​"file.txt"​) ​do​ |file|
 
file.puts ​"Hello, world"
 
end

If we ran this code, we’d get the following ...

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.