Ruby - Standard Input and Output

Introduction

The standard input is a default stream supplied by many operating systems.

By default, the standard input is the keyboard.

You can redirect data to a Ruby application from a Unix-like operating system, such as Linux or Mac OS X, the standard input would be the data piped to it.

For example, let's assume we put the following code example into a file called test.rb.

a = gets 
puts a 

and then ran it like so:

ruby test.rb < somedata.txt 

The output would be the first line of somedata.txt.

gets method would retrieve a single line from the standard input that, in this case, would be the contents of the file somedata.txt.

Here, the Ruby script are being redirected to a file, that destination file becomes the target for the standard output.

Example

You can read multiple lines in one go by using readlines:

lines = readlines 

readlines accepts line after line of input until a terminator, most commonly known as EOF (End Of File), is found.

You can create EOF on most platforms by pressing Ctrl+D.

When the terminating line is found, all the lines of input given are put into an array that's assigned to lines.

This is ideal to accept piped or redirected input on standard input.

For example, the linecount.rb contains this single line:

puts readlines.length 

and you pass in a text file containing ten lines:

ruby linecount.rb < textfile.txt 

you get this result:

10 

Related Topic