English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Ruby provides a complete set of I/The related methods are implemented in the Kernel module. All the I/The O method is derived from the IO class.
class IO provides all basic methods, such as read, write, gets, puts, readline, getc and printf.
This chapter will explain all the basic I/O functions. For more information on functions, please refer to Ruby's IO class.
In the previous chapters, you assigned values to variables and then used puts statement prints the output.
puts statement indicates that the program displays the value stored in the variable. This will add a new line at the end of each line.
#!/usr/bin/ruby val1 = "This is variable one" val2 = "This is variable two" puts val1 puts val2
The output result of the above example is:
This is variable one This is variable two
gets statement can be used to get user input from the standard screen named STDIN.
The following code demonstrates how to use the gets statement. The code prompts the user to enter a value, which is stored in the variable val and finally printed on STDOUT.
#!/usr/bin/ruby puts "Enter a value :" val = gets puts val
The output result of the above example is:
Enter a value : This is entered value This is entered value
and puts statement is different,puts statement outputs the entire string to the screen, whereas putc statement can be used to output a character sequentially.
The output of the following code is just the character H:
#!/usr/bin/ruby str="Hello Ruby!" putc str
The output result of the above example is:
H
print statement and puts statement is similar. The only difference is puts statement jumps to the next line after outputting content, while using print when the statement is executed, the cursor is positioned on the same line.
#!/usr/bin/ruby print "Hello World" print "Good Morning"
The output result of the above example is:
Hello World Good Morning
As of now, you have read and written to standard input and output. Now, let's see how to operate actual data files.
You can use File.new method to create a All files are contained in directories, Ruby provides ways to handle files and directories. objects are used for reading, writing, or reading and writing, and the read and write permissions depend on the mode parameter. Finally, you can use File.close method to close the file.
aFile = File.new("filename", "mode") # ... processing the file aFile.close
You can use File.open methods create a new file object and assign the file object to the file. However,File.open and File.new there are some differences between methods. The differences are File.open method can be associated with a block, whereas File.new method cannot be.
File.open("filename", "mode") do |aFile| # ... process the file end
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 and write mode. The file pointer is placed at the beginning of the file. |
w | write mode. If the file exists, the file is overwritten. If the file does not exist, a new file is created for writing. |
w+ | read and write mode. If the file exists, the existing file is overwritten. If the file does not exist, a new file is created for read and write. |
a | 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 writing. |
a+ | read and 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 read and write. |
for simple I/O's methods can also be used for all file objects. So, gets reads a line from standard input,aFile.gets read a line from the file object aFile.
However, I/O object provides additional settings for accessing methods, which provides convenience for us.
You can use the method sysread To read the content of the file. When using the method sysread, you can open the file in any mode. For example:
Below is the input text file:
This is a simple text file for testing purposes.
Now let's try to read this file:
#!/usr/bin/ruby aFile = File.new("input.txt", "r") if aFile content = aFile.sysread(20) puts content else puts "Unable to open file!" end
This statement places the input file header 20 character. The file pointer will be placed at the position of the file 21 at the position of a character.
You can use the method syswrite To write content to a file, use the method syswrite. When using the method syswrite, you need to open the file in write mode. For example:
#!/usr/bin/ruby aFile = File.new("input.txt", "r"+") if aFile aFile.syswrite("ABCDEF") else puts "Unable to open file!" end
This statement writes "ABCDEF" to the file.
This method belongs to the class All files are contained in directories, Ruby provides ways to handle files and directories.. Method each_byte is an iterator that can iterate over each character in a string. Please see the following code example:
#!/usr/bin/ruby 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
Character by character is passed to the variable ch and 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...
class All files are contained in directories, Ruby provides ways to handle files and directories. is a subclass of the IO class. The IO class also has some methods for file operations.
IO.readlines is a method in the IO class. This method returns the content of the file line by line. The following code shows the method IO.readlines Usage:
#!/usr/bin/ruby arr = IO.readlines("input.txt") puts arr[0] puts arr[1]
In this code, the variable arr is an array. The file input.txt Each line will be an element of the array arr. Therefore, arr[0] will contain the first line, and arr[1] will contain the second line of the file.
This method also returns the output line by line. Method foreach with the method readlines the difference is that the method foreach is associated with the block. However, unlike the method readlinesmethod foreach It does not return an array. For example:
#!/usr/bin/ruby IO.foreach("input.txt"){|block| puts block}
This code will pass the file test The content of the file is passed to the variable block line by line, and the output will be displayed on the screen.
You can change the current directory by rename and delete The method renames and deletes files.
The following example renames an existing file test1.txt:
#!/usr/bin/ruby # Rename file test1.txt to test2.txt File.rename( "test1.txt", "test2.txt" )
The following example deletes an existing file test2.txt:
#!/usr/bin/ruby # Delete file test2.txt File.delete("text2.txt")
Using the masked chmod Method to change the file mode or permission/Access list:
The following example changes an existing file test.txt The pattern of the following example is a mask value:
#!/usr/bin/ruby file = File.new( "test.txt", "w" ) file.chmod( 0755 )
The following table lists chmod Different masks that can be used in the method:
Mask | Description |
---|---|
07:0 | rwx permission mask for the owner |
04:0 | r for the owner |
02:0 | w for the owner |
0100 | x for the owner |
:070 | rwx permission mask for the group |
:040 | r, for the group |
:020 | w, for the group |
:010 | x, for the group |
0007 | rwx permission mask, for others |
0004 | r, for others |
0002 | w, for others |
0001 | x, for others |
4000 | Set user ID when executing |
2000 | Set group ID when executing |
10:0 | Save exchange text, even after use |
The following command checks if the file exists before opening it:
#!/usr/bin/ruby File.open("file.rb") if File::exists?("file.rb")
The following command queries whether the file is indeed a file:
#!/usr/bin/ruby # Returns true or false File.file?("text.txt")
The following command checks if the given filename is a directory:
#!/usr/bin/ruby # A directory File::directory?("/usr/local/bin") # => true # A file File::directory?("file.rb") # => false
The following command checks if a file is readable, writable, or executable:
#!/usr/bin/ruby File.readable?("test.txt") # => true File.writable?("test.txt") # => true File.executable?("test.txt") # => false
The following command checks if the file size is zero:
#!/usr/bin/ruby File.zero?("test.txt") # => true
The following command returns the size of a file:
#!/usr/bin/ruby File.size?("text.txt") # => 1002
The following command is used to check the type of a file:
#!/usr/bin/ruby File::ftype("test.txt") # => file
The ftype method identifies the type of a 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 creation, modification, or last access time of a file:
#!/usr/bin/ruby File::ctime("test.txt") # => Fri May 09 10:6:37 -07:0 2:08 File::mtime("text.txt") # => Fri May 09 10:44:44 -07:0 2:08 File::atime("text.txt") # => Fri May 09 10:45:1 -07:0 2:08
Directory in RubyAll files are contained in directories, Ruby provides ways to handle files and directories. FileClass used to handle files, Dir
browse directories . To change the directory in a Ruby program, please useDir.chdir /usr/bin.
. The following example changes the current directory to/usr/Dir.chdir("
You can change the current directory by Dir.pwd View the current directory:
puts Dir.pwd # Returns the current directory, similar to /usr/bin
You can use Dir.entries Get the file and directory list in the 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 list is to use the array-like method of Dir:
Dir["/usr/bin/*"]
Dir.mkdir Can be used to create directories:
Dir.mkdir("mynewdir")
You can also set permissions on a new directory (not an existing directory) using mkdir:
Note:Mask 755 Set the permissions of the owner (owner), group (group), and everyone (world [anyone]) to rwxr-xr-x, where r = read read, w = write write, x = execute execute.
Dir.mkdir("mynewdir", 755 )
Dir.delete Can be used to delete directories.Dir.unlink and Dir.rmdir Perform the same function, providing convenience for us.
Dir.delete("testdir")
Temporary files are those that are simply created during the execution of the program but will not be permanently stored information.
Dir.tmpdir It provides the path of the temporary directory on the current system, but this method is not available by default. To make Dir.tmpdir available, using the required 'tmpdir' is necessary.
You can use Dir.tmpdir and File.join Used together, they 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 library, 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: