Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

13. Files and IO

Chapter 13. Files and IO

image with no caption

Ruby provides classes dedicated to handling input and output (IO). Chief among these is a class called, unsurprisingly, IO. The IO class lets you open and close IO streams (sequences of bytes) and read and write data to and from them.

For example, assuming you have a file called textfile.txt, containing some lines of text, this is how you might open the file and display each line on the screen:

io_test.rb

IO.foreach("testfile.txt") {|line| print( line ) }

Here foreach is a class method of IO, so you don’t need to create a new IO object to use it; instead, you just specify the filename as an argument. The foreach method takes a block into which each line that is read from the file is passed as an argument. You don’t have to open the file for reading and close it when you’ve finished (as you might expect from your experience with other languages) because Ruby’s IO.foreach method does this for you.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint