The Rubyist Historian: Working With Advanced Data
In this section, a whole new world of programing is about to open before your eyes. So far, we’ve been working with simple data inputs through the use of .gets(), but the method only allows us to call upon a single data entry. What would be infinitely more useful would be the ability to read files outside the program. We can do this with Ruby’s
When working with files, you have some options about how you want to access them. These are called mode specifiers and describes read/write characteristics of the file:
r+ (read/write text, or append data),
r (read only),
w (write only), and
w+ (read/write, but destructive because it destroys whatever existed in the file previously).
Imagine we have a primary source document we would like to read. You can download this file from Github to your local disk for something to work with (this is a letter from a Civil War soldier). We’re going to ask Ruby to read the file and print the results to the screen:
We could also print out specific lines of the array:
The program will print the specified lines to the screen.
We can also write to files using
After running the program. it will will create the file
my_file in the directory you are working in. The file should contain the contents we wrote.
You now know how to read and write files. A whole new world of programming should be opening before you.
- Read/Write Files, Coding Friends
- Working with Files in Ruby, Techtopia
- Ruby File Manipulation Basics, Ben Woodall
See something that’s wrong? Examples that don’t work? Explanations that are unclear or confusing? Embarrassing typographic errors? Drop me an email at jason.heppler+feedback at gmail and I’ll fix things right up!
Topic structure, examples, and explanations for the Rubyist Historian are inspired by, credited to, and drawn from Stephen Ramsay and his course Electronic Text.