Ruby File Input and Output
Ruby provides a complete set of I/O-related methods, implemented in the Kernel module. All I/O methods are derived from the IO class.
ClassIOProvides all the basic methods, such asread、 write、 gets、 puts、 readline、 getcandprintf。
This chapter will explain all the basic I/O functions available in Ruby. For more functions, please refer to Ruby'sIOclass.
putsStatement
In the previous chapters, you assigned values to variables and then used theputsstatement to print output.
putsThe statement instructs the program to display the value stored in the variable. This adds a newline at the end of each line.
Example
The output of the above example is:
This is variable one This is variable two
getsStatement
getsThe statement can be used to obtain user input from the standard input named STDIN.
Example
The following code demonstrates how to use the gets statement. This code prompts the user to enter a value, the value will be stored in the variable val, and finally printed to STDOUT.
Example
The output of the above example is:
Enter a value : This is entered value This is entered value
putcStatement
andputsUnlike the statement,putsthe statement outputs the entire string to the screen, whileputcthe statement can be used to output one character at a time.
Example
The output of the following code is just the character H:
Example
The output of the above example is:
H
printStatement
printThe statement is similar to theputsstatement. The only difference is thatputsthe statement jumps to the next line after outputting content, while using theprintstatement, the cursor is positioned on the same line.
Example
The output of the above example is:
Hello WorldGood Morning
Opening and Closing Files
So far, you have read from and written to standard input and output. Now, we will see how to operate on actual data files.
File.newMethod
You can use theFile.newmethod to create aFileobject for reading, writing, or both, depending on the mode parameter. Finally, you can use theFile.closemethod to close the file.
Syntax
File.openMethod
You can use theFile.openmethod to create a new file object and assign that file object to a file. However,File.openandFile.newthere is a slight difference between the methods. The difference is thatFile.openthe method can be associated with a block, whereasFile.newthe method cannot.
The following table lists the different modes for opening files:
| Mode | Description |
|---|---|
| r | Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. |
| r+ | Read-write mode. The file pointer is placed at the beginning of the file. |
| w | Write-only mode. If the file exists, it overwrites the file. If the file does not exist, a new file is created for writing. |
| w+ | Read-write mode. If the file exists, it overwrites the existing file. If the file does not exist, a new file is created for reading and writing. |
| a | Write-only mode. If the file exists, the file pointer is placed at the end of the file. That is, the file is in append mode. If the file does not exist, a new file is created for writing. |
| a+ | Read-write mode. If the file exists, the file pointer is placed at the end of the file. That is, the file is in append mode. If the file does not exist, a new file is created for reading and writing. |
Reading and Writing Files
Methods used for simple I/O can also be used with all file objects. So, gets reads a line from standard input,aFile.getsand reads a line from the file object aFile.
However, I/O objects provide additional settings for access methods, which brings us convenience.
sysreadMethod
You can use the methodsysreadto read the contents of a file. When using the sysread method, you can open the file in any mode. For example:
The following is the input text file:
This is a simple text file for testing purpose.
Now let us try to read this file:
Example
This statement reads the first 20 characters of the input file. The file pointer will be placed at the position of the 21st character in the file.
syswriteMethod
You can use the methodsyswriteto write content to a file. When using the syswrite method, you need to open the file in write mode. For example:
Example
This statement will write "ABCDEF" to the file.
each_byteMethod
This method belongs to the classFile. The methodeach_byteis an iterator that iterates over each character in a string. Look at the following code example:
Example
The characters are passed one by one to the variable ch, and then displayed on the screen, as shown below:
A.B.C.D.E.F.s. .a. .s.i.m.p.l.e. .t.e.x.t. .f.i.l.e. .f.o.r. .t.e.s.t.i.n.g. .p.u.r.p.o.s.e...
IO.readlinesMethod
ClassFileis a subclass of the IO class. The IO class also has some methods for manipulating files.
IO.readlinesis a method in the IO class. This method returns the contents of the file line by line. The following code shows the methodIO.readlinesusage:
Example
In this code, the variable arr is an array. The fileinput.txthas each line as an element in the array arr. Therefore, arr
IO.foreachMethod
This method also returns output line by line. The methodforeachand the methodreadlinesdiffer in that the methodforeachis associated with a block. However, unlike the methodreadlines, the methodforeachdoes not return an array. For example:
Example
This code will pass the file'stestcontent line by line to the variable block, and then the output will be displayed on the screen.
Renaming and Deleting Files
You can use therenameanddeletemethod to rename and delete files.
The following example renames an existing filetest1.txt:
Example
The following example deletes an existing filetest2.txt:
Example
File Modes and Ownership
Using thechmodmethod with a mask to change the mode or permission/access list of a file:
The following example changes the mode of an existing filetest.txtto a mask value:
Example
The following table lists thechmoddifferent masks that can be used in the method:
| Mask | Description |
|---|---|
| 0700 | rwx mask for the owner |
| 0400 | r, for the owner |
| 0200 | w, for the owner |
| 0100 | x, for the owner |
| 0070 | rwx mask for the group |
| 0040 | r, for the group |
| 0020 | w, for the group |
| 0010 | x, for the group |
| 0007 | rwx mask for others |
| 0004 | r, for others |
| 0002 | w, for others |
| 0001 | x, for others |
| 4000 | Set user ID on execution |
| 2000 | Set group ID on execution |
| 1000 | Save swapped text, even after use |
File Queries
The following command checks whether the file exists before opening the file:
Example
The following command checks whether the file is indeed a file:
Example
The following command checks whether the given file name is a directory:
Example
The following command checks whether the file is readable, writable, and executable:
Example
The following command checks whether the file size is zero:
Example
The following command returns the size of the file:
Example
The following command is used to check the type of the file:
Example
The ftype method identifies the type of the file by returning one of the following values:file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown。
The following command is used to check the time the file was created, modified, or last accessed:
Example
Directories in Ruby
All files are contained in directories, and Ruby provides ways to handle files and directories.FileThe File class is used to handle files,Dirand the Dir class is used to handle directories.
Browsing Directories
To change directories in a Ruby program, useDir.chdir. The following example changes the current directory to/usr/bin。
You can use Dir.pwdto view the current directory:
You can useDir.entriesto get the list of files and directories in the specified directory:
Dir.entriesReturns an array containing all items in the specified directory.Dir.foreachProvides the same functionality:
A more concise way to obtain a directory listing is to use Dir's array-like methods:
Creating Directories
Dir.mkdirCan be used to create directories:
You can also set permissions on a new directory (not an existing directory) via mkdir:
Note:Mask 755 sets the permissions for owner, group, and world (anyone) to rwxr-xr-x, where r = read, w = write, x = execute.
Deleting Directories
Dir.deleteCan be used to delete a directory.Dir.unlinkandDir.rmdirPerforms the same function, providing us with convenience.
Creating Files & Temporary Directories
Temporary files are information that is simply created during program execution but is not stored permanently.
Dir.tmpdirprovides the path to the temporary directory on the current system, but this method is not available by default. To makeDir.tmpdiravailable, it is necessary to require 'tmpdir'.
You can useDir.tmpdirandFile.jointogether to create a platform-independent temporary file:
This code creates a temporary file, writes data to it, and then deletes the file. Ruby's standard library also includes a library namedTempfilelibrary, which can be used to create temporary files:
Built-in Functions
The following provides a complete list of built-in functions for handling files and directories in Ruby:
Other Extensions