September 2015
Intermediate to advanced
200 pages
6h 40m
English
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 ...
Read now
Unlock full access