Reading and Writing Files

The same methods that we’ve been using for “simple” I/O from standard input and output are available for File objects. So, where Kernel#gets reads a line from standard input (or from any files specified on the command line when the script was invoked), File#gets reads a line from the file object.

For example, we could create a program called copy.rb:

 while​ (line = gets)
  puts line
 end

If we run this program with no arguments, it’ll read lines from the console and copy them back to the console. Note that each line is echoed once the Return key is pressed. (In this and later examples, we show user input in a bold font.) The ^D is the end-of-file character on Unix systems.

 $ ​​ruby​​ ​​copy.rb

Get Programming Ruby 3.3 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.