Opening and reading files - the ruby fundamentals
Archive - Originally posted on "The Horse's Mouth" - 2009-07-16 05:20:07 - Graham EllisOnce you've noted that File.new doesn't create a new file, but rather (default) opens an existing one for read ... you'll find Ruby's file handling interface easy to use. The new methof returns a file handle object - a sort of buffer that sits between the file and your program - and each time you run the gets method on it, you'll get the next line back. Once you hit the end of the file, you'll get a nil result which you can check for, and you're then supposed to close the file.
Once you've hit the end of the file, further calls to gets will simply return nil again; if you want to re-read the data, you'll have to open the file again, or use a rewind method. Of course, you could read the whole file into an array with readlines and then iterate through it a lot of times without going back to the disc, and that's going to be much quicker unless the file is huge.
The File class also has a number of methods like exists and size which allow you to check a file status even without opening it
[link] Iterating through a file, and file output.
[link] Test file to see if it exists prior to opening.
You can also open another process and handle that as it it were a file:
[link] Reading from another process
Examples written yesterday during our Learning to program in Ruby Course. Similar principles apply across many of the langauges we teach with just the deatil and syntax varying, and we can also run "Learning to program in ..." courses in Python, Lua, PHP, ....