A Ruby file object is an open connection to a file. Create one with `File.new("temp.dat")`, then use the returned object to read from that file. `File` is a subclass of `IO`, so its objects share stream operations with other I/O objects. Opening a nonexistent file for reading raises an exception. section 12.2 section 12.2.1
Write a conversion result
After calculating a Fahrenheit value, `fh = File.new("temp.out", "w")` opens an output file; `fh.puts fahrenheit` writes the value, and `fh.close` closes the handle. The variable `fh` refers to the open file object, not to the filename string. section 1.1.7
The object keeps track of both how it was opened and where reading has reached:
- `read` returns the remaining file contents as one string. For line-by-line work, `gets` returns the next line; at end of file it returns `nil`, whereas `readline` raises `EOFError`. section 12.2.1 section 12.2.2
- `each` iterates over lines without first reading the whole file into an array. `readlines` instead returns an array of lines. section 12.2.2
- `rewind` returns to the beginning. `pos` reports the current byte position; assigning to `pos` or calling `seek` moves it, so the next read can start elsewhere. section 12.2.4
- Writing requires a suitable mode: `"w"` creates or overwrites a file, while `"a"` creates one or appends to its existing contents. Use `puts`, `print`, or `write` on the open object. section 12.2.6
An object opened with `File.new` needs an explicit `close` when the operation is finished. Alternatively, `File.open("records.txt") do |f| ... end` passes the file object into a block and closes it when the block ends. The block does not read automatically: call `gets`, `each`, or another reading method inside it. section 12.2.1 section 12.2.7
Process records one line at a time
`File.open("records.txt") do |f|; while record = f.gets; puts record.chomp; end; end` keeps the handle inside the block. The loop stops when `gets` returns `nil`; leaving the block closes the file. section 12.2.7
The handle pattern extends beyond disk files: an I/O handle connected to an external program can also receive `puts`, supply data through `gets`, and be closed. section 14.6.2







