In this part of the Ruby tutorial, we will talk about input & output operations in Ruby. Input is any data that is read by the program, either from a keyboard, file or other programs. Output is data that is produced by the program. The output may go to the screen, to a file or to another program.
Input & output is a large topic. We bring forward some examples to give you a general idea of the subject. Several classes in Ruby have methods for doing input & output operations. For example Kernel, IO, Dir or File.
Writing to console
Ruby has several methods for printing output on the console. These methods are part of the Kernel module. Methods of the Kernel are available to all objects in Ruby.
According to the Ruby documentation, the print method is an equivalent to the $stdout.print. The $stdout is a global variable which holds the standard output stream.
Reading input from console
The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console.
The common way to read data from the console is to use the gets method.
To remove the newline character, we can use chomp method.
From the official Ruby documentation we learn that the IO class is the basis for all input and output in Ruby. The File class is the only subclass of the IO class. The two classes are closely related. In the first example, we open a file and write some data to it:
In this section, we work with directories. We have a Dir class to work with directories in Ruby.
The third example works with a home directory. Every user in a computer has a unique directory assigned to him. It is called a home directory. It is a place where he can place his files and create his own hierarchy of directories.
Ruby has several ways to execute external programs. We will deal with some of them. In our examples we will use well known Linux commands. Readers with Windows or Mac can use commands specific for their systems.
Below show two other ways of running external programs in Ruby.
We can execute a command with the open method. The method belongs to the Kernel module. It creates an IO object connected to the given stream, file, or subprocess. If we want to connect to a subprocess, we start the path of the open with a pipe character |.
Redirecting standard output
Ruby has predefined global variables for standard input, standard output and standard error output. The $stdout is the name of the variable for the standard output. In the below example, we redirect a standard output to the output.log file.