Files and text
A script that reads a file and prints a report is most of the work a Ruby program does. Files and IO open the part, then reading and writing, paths and directories, binary streams, file metadata and permissions, and watching a file for changes. The text half covers string tools, the output methods, ERB templates, regular expressions, scanning and parsing, a text pipeline and tables in the terminal.
8.1
Files and IO
Read and write files and list directories with Ruby IO tools.
Open
8.2
Reading and writing files
File.read and File.write for a whole file, the append mode that adds a line instead of replacing it, and File.foreach for a file too big to load.
Open
8.3
Paths and directories
Pathname for a path that knows its parts, File.join for one separator, Dir.glob for a pattern and Dir.mktmpdir for scratch space, none of which depend on the system separator.
Open
8.4
Binary files and streams
bytesize against length, binread and binwrite for data that is not text, reading a file in chunks, and IO.copy_stream for moving bytes without a buffer in Ruby.
Open
8.5
File metadata and permissions
File.stat for size, mode and times, chmod to change the mode, expand_path to make a path absolute, symlinks that stat follows and lstat does not, and a small report.
Open
8.6
Watching files for changes
File.mtime is the cheapest way to notice an edit, a loop with a deadline is the way to wait for one, and polling misses changes that a real watcher would see.
Open
8.7
String tools
Split, replace, match, and format strings with Ruby string tools.
Open
8.8
puts, print and p
Print text with puts and print and inspect values with p.
Open
8.9
ERB templates
Render text with ERB, from inline strings and files to trim mode and layouts.
Open
8.10
Regular expressions
match and =~, named captures, gsub with a block, and a regex that validates a log line without splitting it into pieces.
Open
8.11
Scanning and parsing strings
scan with groups, split on a regex, StringScanner for a small grammar, and a key-value parser built from six lines of it.
Open
8.12
A text pipeline
A script that reads a log line by line, validates each line with a regex, counts the failing paths in a hash and prints a report a pipeline can read.
Open
8.13
Formatting tables in the terminal
Count columns from the data, pad with ljust, draw a border with a string, and emit the same rows as CSV for another program.
Open