Ruby provides a complete set of Istroke O-related methods, implemented in kernel (Kernel) modules. All the Icano methods are derived from the IO class.
Class IO provides all the basic methods, such as *read 、 write 、 gets 、 puts 、 readline 、 getc* and printf .
This section will cover all the basic Imax O functions available in Ruby. For more functions, check out Ruby’s IO class. In the previous section, you assigned a value to a variable and then used the The output of the above instance is as follows: The following code demonstrates how to use the The output of the above instance is as follows: Different from the The output of the following code is just characters The output of the above instance is as follows: The output of the above instance is as follows: As of now, you have read and written standard input and output. Now, we willlook at how to manipulate the actual data file. You can use the You can use the The following table lists the different modes for opening files: Pattern 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 the mode. If the file exists, overwrite the file. If the file does not exist, a new file is created for writing. W + Read-write mode. If the file exists, the existing file is overwritten. If the file does not exist, create a new file for reading and writing. A Write only the 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, create a new file for reading and writing. The method for simple Icano can also be used for all However, the Imap O object provides additional settings for accessing methods, which makes it convenient for us. You can use the method The following is the input text file: Now let’s try to read this file: This statement will enter the first 20 characters of the file. The file pointer will be placed in the position of the 21st character in the file. You can use the method This statement will write “ABCDEF” to the file. This method belongs to the class One character after another is passed to the variable ch and then displayed on the screen, as shown below: Class In this code, the variable This method also returns output line by line. Method This code will put the file You can use the The following example renames an existing file The following example deletes an existing file Use masked The following example changes an existing file The following table lists Mask Description 0700 Rwx mask for owner 0400 R, for the owner 0200 W, for the owner 0100 X, for the owner 0070 Rwx mask for the group it belongs to 0040 R for the group to which it belongs 0020 W for the group to which it belongs 0010 X, for the group 0007 Rwx mask for other people 0004 R, aimed at other people 0002 W, aimed at other people 0001 X, for other people 4000 Set user ID at execution time 2000 Set the group ID when executing 1000 Save the exchange text, even after use The following command checks whether the file already exists before opening it: The following command queries whether the file is indeed a file: The following command checks whether the given file name is a directory: The following command checks whether the file is readable, writable, and executable: The following command checks whether the file size is zero: The following command returns the size of the file: The following command checks the type of file: The following command is used to check when the file was created, modified, or last accessed: All files are contained in directories, and Ruby provides a way to deal withfiles and directories. To change the directory in the Ruby program, use the You can use the You can use the A more concise way to get a directory list is by using the You can also use the Note: mask 755 sets owner (owner), group (group), everyone (world) [anyone] The permissions for) are Temporary files are information that is simply created during program execution but is not permanently stored. The You can put This code creates a temporary file, writes data to it, and then deletes the file. The standard library of Ruby also contains a library called The following provides a complete list of built-in functions in Ruby that deal with files and directories: File classes and methods. Dir classes and methods. 6.27.1.
puts statement # puts statement printout. puts statement instructs the program to display the value stored in the variable. This adds a new line at the end of each line.Example #
#!/usr/bin/rubyval1="This is variable one"val2="This is variable two"putsval1putsval2
This is variable one This is variable two
6.27.2.
gets statement # gets statement can be used to get data from a file named STDIN the user input of the standard screen of 6.27.3. Example #
gets statement. The code will prompt the user for a value that will be stored in the variable val will eventually be printed in the STDOUT go.Example #
#!/usr/bin/rubyputs"Enter a value :"val=getsputsval Enter a value : This is entered value This is entered value
6.27.4.
putc statement # puts statement, puts statement outputs the entire string to the screen, while the putc statement can be used to output one character in turn. 6.27.5. Example #
H :Example #
#!/usr/bin/rubystr="Hello Ruby!"putcstr H 6.27.6.
print statement # print statement vs puts statement is similar. The only difference is that puts statement jumps to the next line after the output, using the print statement, the cursor is positioned on the same line.Example #
#!/usr/bin/rubyprint"Hello World"print"Good Morning" Hello WorldGood Morning
6.27.7. Open and close files #
6.27.8.
File.new method # File.new method to create a File object is used toread, write, or read and write, and the read and write permissions depend on the mode parameters. Finally, you can use the File.close methodto close the file.Grammar #
aFile=File.new("filename","mode")#... process the file aFile.close
6.27.9.
File.open method # File.open method to create a new file object and set the file object is assigned to the file. But, File.open and There is a slight difference between File.new methods. The difference isthat File.open method can be associated with a block, while the File.new the method can’t.File.open("filename","mode")do\|aFile\|#... process the fileend
6.27.10. Read and write files #
file object. So, gets reads a row from standard input aFile.gets from file object aFile read a row. 6.27.11. sysread method #
sysread to read the contents of the file. When using method sysread you can open the file in any mode. For example:This is a simple text file for testing purpose.
Example #
#!/usr/bin/rubyaFile=File.new("input.txt","r")ifaFilecontent=aFile.sysread(20)putscontentelseputs"Unable to open file!"end 6.27.12.
syswrite method # syswrite to write to the file. When using method syswrite need to open the file in write mode. For example:Example #
#!/usr/bin/rubyaFile=File.new("input.txt","r+")ifaFileaFile.syswrite("ABCDEF")elseputs"Unable to open file!"end 6.27.13. each_byte Method #
File . each_byte method is an iterator that iterates over each character in a string. Take a look at the following code example:Example #
#!/usr/bin/rubyaFile=File.new("input.txt","r+")ifaFileaFile.syswrite("ABCDEF")aFile.rewindaFile.each_byte{\|ch\|putcch;putc?. }elseputs"Unable to open file!"end
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...
6.27.14.
IO.readlines method # File is a subclass of the class IO. The class IO 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 method IO.readlines use:Example #
#!/usr/bin/rubyarr=IO.readlines("input.txt")putsarr[0]putsarr[1] arr is an array. File input.txt each row of will be an array arr an element in the. Therefore, arr [0] will contain the first line, while arr[1] the second line of the filewill be included. 6.27.15.
IO.foreach method # foreach and methods readlines . The difference between them is that the method foreach associated with a block. But, unlike the method, readlines , method foreach instead of returning an array. For example:Example #
#!/usr/bin/rubyIO.foreach("input.txt"){\|block\|putsblock} test is passed to the variable line by line block and then the output is displayed on the screen. 6.27.16. Rename and delete files #
rename and delete method to rename and delete files. test1.txt :Example #
#!/usr/bin/ruby# rename the file test1. txt to test2.txtFile.rename("test1.txt","test2.txt")
test2.txt :Example #
#!/usr/bin/ruby# delete file test2.txtFile.delete("text2.txt") 6.27.17. File mode and ownership #
chmod method to change the mode or permission / access list of the file: test.txt is a mask valueExample #
#!/usr/bin/rubyfile=File.new("test.txt","w")file.chmod(0755) chmod the different masks that can be used in the 6.27.18. File query #
Example #
#!/usr/bin/rubyFile.open("file.rb")ifFile::exists?("file.rb") Example #
#!/usr/bin/ruby# return true or falseFile.file?("text.txt") Example #
#!/usr/bin/ruby# A directory File::directory?("/usr/local/bin")#=> true# A directory File::directory?("file.rb")#=> false
Example #
#!/usr/bin/rubyFile.readable?("test.txt")#=> trueFile.writable?("test.txt")#=> trueFile.executable?("test.txt")#=> false Example #
#!/usr/bin/rubyFile.zero?("test.txt")#=> true Example #
#!/usr/bin/rubyFile.size?("text.txt")#=> 1002 Example #
#!/usr/bin/rubyFile::ftype("test.txt")#=> file ftype Method identifies the type of file by returning one of the following values: *file 、 directory 、 characterSpecial 、 blockSpecial 、 fifo 、 link 、 socket or unknown* .Example #
#!/usr/bin/rubyFile::ctime("test.txt")#=> Fri May 09 10:06:37 -0700 2008File::mtime("text.txt")#=> Fri May 09 10:44:44 -0700 2008File::atime("text.txt")#=> Fri May 09 10:45:01 -0700 2008
6.27.19. Directories in Ruby #
File class is used to process files Dir class is used to process directories. 6.27.20. Browse the catalog #
Dir.chdir . The following example changes the current directory to /usr/bin .Dir.chdir("/usr/bin")
Dir.pwd view the current directory:putsDir.pwd# Return to the current directory, similar to /usr/bin
Dir.entries get a list of files and directories in the specified directory:putsDir.entries("/usr/bin").join('')
Dir.entries returns an array of all items in the specified directory. Dir.foreach provides the same functionality:Dir.foreach("/usr/bin")do\|entry\|putsentryend
Dir the method of the class array ofDir["/usr/bin/*"]
6.27.21. Create a directory #
Dir.mkdir can be used to create directories:Dir.mkdir("mynewdir")
mkdir set permissions on the new directory (not anexisting directory): rwxr-xr-x , of which r = read read, w =write write x = execute execute.Dir.mkdir("mynewdir",755)
6.27.22. Delete directory #
Dir.delete can be used to delete directories. Dir.unlink and Dir.rmdir are convenient for us to perform the same function.Dir.delete("testdir")
6.27.23. Create a file & temporary directory #
Dir.tmpdir path to the temporary directory on the current system is provided, but this method is not available by default. In order to make Dir.tmpdir available, use the necessary 'tmpdir' is necessary. Dir.tmpdir and File.join to use together to create a temporary file independent of the platform:require'tmpdir'tempfilename=File.join(Dir.tmpdir,"tingtong")tempfile=File.new(tempfilename,"w")tempfile.puts"This is a temporary file"tempfile.closeFile.delete(tempfilename)
Tempfile that can be used to create temporary filesrequire'tempfile'f=Tempfile.new('tingtong')f.puts"Hello"putsf.pathf.close
6.27.24. Built-in function #