Preface
This chapter introduces the input and output of Ruby's iterators and files.
Ruby iterator
Simply put: iterate refers to repeating the same thing, so iterator is used to repeat the same thing many times.
Iterators are methods supported by collections. An object that stores a set of data members is called a collection. In Ruby, arrays (Array) and hash (Hash) can be called collections.
The iterator returns all elements of the collection, one after another. Here we will discuss two iterators, each and collect.
Ruby each iterator
Each iterator returns all elements of an array or hash.
grammar
do |variable| code end
Execute code for each element in the collection. Here, the collection can be an array or a hash.
Example
#!/usr/bin/ruby ary = [1,2,3,4,5] do |i| puts i end
The output results of the above example operation are:
1 2 3 4 5
Each iterator is always associated with a block. It returns each value of the array to the block, one after another. The value is stored in the variable i and then displayed on the screen.
Ruby collect iterator
The collect iterator returns all elements of the collection.
grammar
collection =
The collect method does not need to be always associated with a block. The collect method returns the entire collection, whether it is an array or a hash.
Example
#!/usr/bin/ruby a = [1,2,3,4,5] b = b = { |x|x } puts b
The output results of the above example operation are:
1 2 3 4 5
Note: The collect method is not the correct way to copy between arrays. Here is another method called clone for copying an array to another.
When you want to do some operations on each value in order to get a new array, you usually use the collect method. For example, the following code will generate an array whose value is 10 times that of each value in a.
Example
#!/usr/bin/ruby a = [1,2,3,4,5] b = {|x| 10*x} puts b
The output results of the above example operation are:
10 20 30 40 50
Java requires converting Map into List type containers to use iterators, but Ruby has iterators that directly target Map:
sum = 0 cutcome = {"block1" => 1000, "book2" => 1000, "book3" => 4000} {|item, price| sum += price} print "sum = " + sum.to_s
It can even be like this:
sum = 0 cutcome = {"block1" => 1000, "book2" => 1000, "book3" => 4000} {|pair| sum += pair[1]} print "sum = " + sum.to_s
Input and output of Ruby files
Ruby provides a complete set of I/O-related methods, implemented in the kernel (Kernel) module. All I/O methods are derived from IO classes.
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 available in Ruby. For more functions, check out Ruby's IO class.
puts statement
In the previous chapter, you assign values to variables and then print the output using the puts statement.
The puts statement instructs the program to display the values stored in the variable. This will add a new line at the end of each line.
Example
#!/usr/bin/ruby val1 = "This is variable one" val2 = "This is variable two" puts val1 puts val2
The output results of the above example operation are:
This is variable one This is variable two
gets statement
The gets statement can be used to get user input from a standard screen named STDIN.
ExampleThe following code demonstrates how to use the gets statement. The code will prompt the user to enter a value that will be stored in the variable val and will be printed on STDOUT.
Example
#!/usr/bin/ruby puts "Enter a value :" val = gets puts val
The output results of the above example operation are:
Enter a value : This is entered value This is entered value
putc statement
Unlike the puts statement, the puts statement outputs the entire string to the screen, while the putc statement can be used to output one character in turn.
Example
The output of the following code is just the character H:
#!/usr/bin/ruby str="Hello Ruby!" putc str
The output results of the above example operation are:
H
print statement
The print statement is similar to the puts statement. The only difference is that the puts statement will jump to the next line after outputting the content, and when using the print statement, the cursor is positioned on the same line.
Example
#!/usr/bin/ruby print "Hello World" print "Good Morning"
The output results of the above example operation are:
Hello WorldGood Morning
Open and close files
As of now, you have read and write standard input and output. Now, we will see how to manipulate the actual data file.
method
You can use the method to create a File object for reading, writing, or reading, and the read and write permissions depend on the mode parameter. Finally, you can use the method to close the file.
grammar
aFile = ("filename", "mode") # ... Processing files
method
You can use the method to create a new file object and assign the file object to the file. However, there is a little difference between the method and the method. The difference is that a method can be associated with a block, but a method cannot.
("filename", "mode") do |aFile| # ... process the file end
The following table lists the different modes for opening files:
model | describe |
---|---|
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-only mode. If the file exists, rewrite the file. If the file does not exist, a new file is created for writing. |
w+ | Read and write mode. If the file exists, then rewrite 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. In other words, the file is 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. In other words, the file is append mode. If the file does not exist, a new file is created for reading and writing. |
Read and write files
Methods for simple I/O can also be used on all file objects. So, gets reads a line from standard input and a line from file object aFile.
However, I/O objects provide additional settings for access methods, which facilitates us.
sysread method
You can use the method sysread to read the contents of the file. When using method sysread, you can open the file in either 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
#!/usr/bin/ruby aFile = ("", "r") if aFile content = (20) puts content else puts "Unable to open file!" end
This statement will enter the first 20 characters of the file. The file pointer will be placed at the 21st character in the file.
syswrite method
You can use the method syswrite to write content to a file. When using method syswrite, you need to open the file in write mode. For example:
Example
#!/usr/bin/ruby aFile = ("", "r+") if aFile ("ABCDEF") else puts "Unable to open file!" end
This statement will be written to "ABCDEF" into the file.
each_byte method
This method belongs to the class File. The method each_byte is a character that can iterate over each character in a string. Please see the following code example:
Example
#!/usr/bin/ruby aFile = ("", "r+") if aFile ("ABCDEF") aFile.each_byte {|ch| putc ch; putc ?. } else puts "Unable to open file!" end
Characters are passed to the variable ch and then displayed on the screen as follows:
. .a. .. .. .. .. .. ....
method
Class File is a subclass of class IO. Class IO also has some methods for manipulating files.
is a method in the IO class. This method returns the contents of the file line by line. The following code shows the use of the method:
Example
#!/usr/bin/ruby arr = ("") puts arr[0] puts arr[1]
In this code, the variable arr is an array. Each line of the file will be an element in the array arr. Therefore, arr[0] will contain the first line, and arr[1] will contain the second line of the file.
method
This method also returns the output line by line. The difference between method foreach and method readlines is that method foreach is associated with a block. However, unlike methods readlines, method foreach does not return an array. For example:
Example
#!/usr/bin/ruby (""){|block| puts block}
This code will pass the contents of the file test line by line to the variable block, and the output will be displayed on the screen.
Rename and delete files
You can rename and delete files through the rename and delete methods.
The following example renames an existing file:
Example
#!/usr/bin/ruby # Rename the file as( "", "" )
The following example deletes an existing file:
Example
#!/usr/bin/ruby # Delete the file("")
File Mode and Ownership
Use the chmod method with mask to change the pattern or permissions/access list of files:
The following example changes the pattern of an existing file to a mask value:
Example
#!/usr/bin/ruby file = ( "", "w" ) ( 0755 )
The following table lists the different masks that can be used in the chmod method:
Mask | describe |
---|---|
0700 | rwx mask, for owner |
0400 | r, for owner |
0200 | w , for owner |
0100 | x , for owner |
0070 | rwx mask for group |
0040 | r, for the group to which it belongs |
0020 | w , for the group |
0010 | x , for the group to which it belongs |
0007 | rwx mask, targeting others |
0004 | r, targeting others |
0002 | w, targeting other people |
0001 | x , targeting others |
4000 | Set user ID when executing |
2000 | Set the group ID when executing |
1000 | Save the exchange text, even after use |
File Query
The following command checks whether the file already exists before opening it:
Example
#!/usr/bin/ruby ("") if File::exists?( "" )
The following command checks whether the file is indeed a file:
Example
#!/usr/bin/ruby # Return true or false?( "" )
The following command checks whether the given file name is a directory:
Example
#!/usr/bin/ruby # a directoryFile::directory?( "/usr/local/bin" ) # => true # a fileFile::directory?( "" ) # => false
The following commands check whether the file is readable, writable, and executable:
Example
#!/usr/bin/ruby ?( "" ) # => true ?( "" ) # => true ?( "" ) # => false
The following command checks whether the file size is zero:
Example
#!/usr/bin/ruby ?( "" ) # => true
The following command is used to check the file type:
Example
#!/usr/bin/ruby File::ftype( "" ) # => file
The ftype method identifies the file type by returning one of the following values: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.
The following commands are used to check when a file is created, modified, or last accessed:
Example
#!/usr/bin/ruby File::ctime( "" ) # => Fri May 09 10:06:37 -0700 2008 File::mtime( "" ) # => Fri May 09 10:44:44 -0700 2008 File::atime( "" ) # => Fri May 09 10:45:01 -0700 2008
Directory in Ruby
All files are included in directories, and Ruby provides ways to process files and directories. The File class is used to process files, and the Dir class is used to process directories.
Browse the directory
To change the directory in a Ruby program, use . The following example changes the current directory to /usr/bin.
("/usr/bin")
You can view the current directory through:
puts # Return to the current directory, similar to /usr/bin
You can use : Get a list of files and directories in a specified directory:
puts ("/usr/bin").join(' ')
Returns an array containing all items in the specified directory. The same functionality is provided:
("/usr/bin") do |entry| puts entry end
A simpler way to get a directory list is by using Dir's class array:
Dir["/usr/bin/*"]
Create a directory
Can be used to create directories:
("mynewdir")
You can also set permissions on a new directory (not an existing directory) via mkdir:
Note: Mask 755 sets the permissions of the owner, group, and everyone (world [anyone]) to rwxr-xr-x, where r = read read, w = write write, and x = execute.
( "mynewdir", 755 )
Delete Directory
Can be used to delete directories. Performing the same function provides us with convenience.
("testdir")
Create Files & Temporary Directories
Temporary files are information that are simply created during program execution but are not permanently stored.
The path to the temporary directory on the current system is provided, but this method is not available by default. To make it available, the required ‘tmpdir’ is necessary.
You can use , together, to create a temporary file independent of the platform:
require 'tmpdir' tempfilename = (, "tingtong") tempfile = (tempfilename, "w") "This is a temporary file" (tempfilename)
This code creates a temporary file, writes data to it, and then deletes the file. Ruby's standard library also includes a library called Tempfile that can be used to create temporary files:
require 'tempfile' f = ('tingtong') "Hello" puts
This is the article about the input and output of Ruby iterators and files. For more related Ruby iterators and files, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!