YouTip LogoYouTip

Ruby Input Output

Ruby provides a complete set of I/O-related methods, implemented within the Kernel module. All I/O methods are derived from the IO class. The _IO_ class provides all the basic methods, such as _read, write, gets, puts, readline, getc_, and _printf_. This chapter will explain all the basic I/O functions available in Ruby. For more functions, please refer to Ruby's _IO_ class. In previous chapters, you assigned values to variables and then used the _puts_ statement to print output. The _puts_ statement instructs the program to display the value stored in a variable. It adds a new line at the end of each line. ## Example val1 = "This is variable one"val2 = "This is variable two"puts val1 puts val2 The output of the above example is: This is variable one This is variable two The _gets_ statement can be used to get user input from the standard screen, named STDIN. ### Example The following code demonstrates how to use the gets statement. This code will prompt the user to enter a value, which will be stored in the variable val and finally printed on STDOUT. ## Example puts"Enter a value :"val = gets puts val The output of the above example is: Enter a value :This is entered value This is entered value Unlike the _puts_ statement, which outputs the entire string to the screen, the _putc_ statement can be used to output characters one by one. ### Example The output of the following code is just the character H: ## Example str="Hello Ruby!"putc str The output of the above example is: H The _print_ statement is similar to the _puts_ statement. The only difference is that the _puts_ statement moves to the next line after outputting the content, while with the _print_ statement, the cursor stays on the same line. ## Example print"Hello World"print"Good Morning" The output of the above example is: Hello WorldGood Morning So far, you have read from and written to standard input and output. Now, let's see how to work with actual data files. ### _File.new_ Method You can use the _File.new_ method to create a _File_ object for reading, writing, or both, depending on the mode parameter. Finally, you can use the _File.close_ method to close the file. ## Syntax aFile = File.new("filename", "mode")aFile.close ### _File.open_ Method You can use the _File.open_ method to create a new file object and assign it to a file. However, there is a slight difference between the _File.open_ and _File.new_ methods. The difference is that the _File.open_ method can be associated with a block, while the _File.new_ method cannot. File.open("filename", "mode")do |aFile| end The following table lists the different modes for opening a file: | 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 is overwritten. If the file does not exist, a new file is created for writing. | | w+ | Read-write mode. If the file exists, it is overwritten. 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. | The methods used for simple I/O can also be used with all file objects. So, gets reads a line from standard input, and _aFile.gets_ reads a line from the file object aFile. However, I/O objects provide additional settings for accessing methods, which are convenient for us. ### _sysread_ Method You can use the _sysread_ method to read the contents of a file. When using the sysread method, you can open the file in any mode. For example: Here is the input text file: This is a simple text file for testing purpose. Now let's try to read this file: ## Example aFile = File.new("input.txt", "r")if aFile content = aFile.sysread(20)puts content else puts"Unable to open file!"end This statement will read the first 20 characters of the input file. The file pointer will be placed at the position of the 21st character in the file. ### _syswrite_ Method You can use the _syswrite_ method to write content to a file. When using the syswrite method, you need to open the file in write mode. For example: ## Example aFile = File.new("input.txt", "r+")if aFile aFile.syswrite("ABCDEF")else puts"Unable to open file!"end This statement will write "ABCDEF" to the file. ### _each_byte_ Method This method belongs to the _File_ class. The _each_byte_ method iterates over each character in a string. Please see the following code example: ## Example aFile = File.new("input.txt", "r+")if aFile aFile.syswrite("ABCDEF")aFile.rewind aFile.each_byte {|ch| putc ch; putc ?. } else puts"Unable to open file!"end Characters are passed one by one to the variable ch, and then displayed on the screen, as follows: 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.readlines_ Method The _File_ class is a subclass of the IO class. The IO class also has some methods for manipulating files. _IO.readlines_ is a method in the IO class. This method returns the contents of the file line by line. The following code shows the usage of the _IO.readlines_ method: ## Example arr = IO.readlines("input.txt")puts arrputs arr In this code, the variable arr is an array. Each line of the file _input.txt_ will be an element in the array arr. Therefore, arr will contain the first line, and arr will contain the second line of the file. ### _IO.foreach_ Method This method also returns output line by line. The difference between the _foreach_ method and the _readlines_ method is that the _foreach_ method is associated with a block. However, unlike the _readlines_ method, the _foreach_ method does not return an array. For example: ## Example IO.foreach("input.txt"){|block| puts block} This code will pass the contents of the file _test_ line by line to the variable block, and then the output will be displayed on the screen. You can rename and delete files using the _rename_ and _delete_ methods. The following example renames an existing file _test1.txt_: ## Example File.rename("test1.txt", "test2.txt") The following example deletes an existing file _test2.txt_: ## Example File.delete("text2.txt") Use the _chmod_ method with a mask to change the file's mode or permissions/access list: The following example changes the mode of an existing file _test.txt_ to a mask value: ## Example file = File.new("test.txt", "w")file.chmod(0755) The following table lists the different masks that can be used in the _chmod_ 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 | The following command checks if a file exists before opening it: ## Example File.open("file.rb")if File::exists?("file.rb") The following command queries whether a file is indeed a file: ## Example File.file?("text.txt") The following command checks if the given filename is a directory: ## Example File::directory?("/usr/local/bin")File::directory?("file.rb") The following commands check if the file is readable, writable, and executable: ## Example File.readable?("test.txt")File.writable?("test.txt")File.executable?("test.txt") The following command checks if the file size is zero: ## Example File.zero?("test.txt") The following command returns the size of the file: ## Example File.size?("text.txt") The following command is used to check the type of the file: ## Example File::ftype("test.txt") 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 commands are used to check the time when the file was created, modified, or last accessed: ## Example File::ctime("test.txt")File::mtime("text.txt")File::atime("text.txt") All files are contained within directories, and Ruby provides ways to handle files and directories. The _File_ class is used to handle files, and the _Dir_ class is used to handle directories. ### Browsing Directories To change directories in a Ruby program, use _Dir.chdir_. The following example changes the current directory to _/usr/bin_. Dir.chdir("/usr/bin") You can view the current directory using _Dir.pwd_: puts Dir.pwd You can use _Dir.entries_ to get a list of files and directories within a specified directory: puts Dir.entries("/usr/bin").join('') _Dir.entries_ returns an array containing all items in the specified directory. _Dir.foreach_ provides the same functionality: Dir.foreach("/usr/bin")do |entry| puts entry end A more concise way to get a directory listing is by using Dir's class array method: Dir["/usr/bin/*"] ### Creating Directories _Dir.mkdir_ can be used to create directories: Dir.mkdir("mynewdir") You can also set permissions on a new directory (not an existing one) using mkdir: **Note:** The mask 755 sets the permissions for the owner, group, and world to rwxr-xr-x, where r = read, w = write, x = execute. Dir.mkdir("mynewdir", 755) ### Deleting Directories _Dir.delete_ can be used to delete directories. _Dir.unlink_ and _Dir.rmdir_ perform the same function, providing convenience. Dir.delete("testdir") Temporary files are those that are simply created during program execution but are not stored permanently. _Dir.tmpdir_ provides the path to the temporary directory on the current system, but this method is not available by default. To make _Dir.tmpdir_ available, it is necessary to require the 'tmpdir' library. You can use _Dir.tmpdir_ with _File.join_ to create a platform-independent temporary file: require'tmpdir'tempfilename = File.join(Dir.tmpdir, "tingtong")tempfile = File.new(tempfilename, "w")tempfile.puts"This is a temporary file"tempfile.close File.delete(tempfilename) This code creates a temporary file, writes data to it, and then deletes the file. Ruby's standard library also includes a library named _Tempfile_, which can be used to create temporary files: require'tempfile'f = Tempfile.new('tingtong')f.puts"Hello"puts f.path f.close Below is a complete list of built-in functions for handling files and directories in Ruby: . .
← Ruby File MethodsRuby Iterators β†’