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 ...

Get The Book of Ruby now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.