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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.