Once 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, ....
(written 2009-07-16)
Associated topics are indexed under
R106 - Input and Output in Ruby [3429] Searching through all the files in or below a directory - Ruby, Tcl, Perl - (2011-09-09)
[2974] Formatting your output - options available in Ruby - (2010-09-29)
[2893] Exclamation marks and question marks on ruby method names - (2010-07-28)
[2621] Ruby collections and strings - some new examples - (2010-02-03)
[2614] Neatly formatting results into a table - (2010-02-01)
[1887] Ruby Programming Course - Saturday and Sunday - (2008-11-16)
[1587] Some Ruby programming examples from our course - (2008-03-21)
Some other Articles
Can you learn to program in 4 days?Regular Expressions in RubyObject Orientation in Ruby - intermediate examplesCollection objects (array and hash) in RubyOpening and reading files - the ruby fundamentalspre-Inaugural briefing - Melksham Community Area PartnershipWiltshire Community Area PartnershipsLearning to program in Ruby - examples of the programming basicsNew to programming? It is natural (but needless) for you to be nervousGreat new diagrams for our notes ... Python releases