January 2024
Intermediate to advanced
718 pages
20h 15m
English
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 |
Read now
Unlock full access