1 open and close a file
Class method File.new opens a file and instantiates it as a file object, and his first argument is the filename.
The optional second argument is called the mode string (which is also derived from c). He means to open a file (read, write, or otherwise). The default is ' R ' (that is, read).
File1 = File.new ("one") # Open for reading
file2 = file.new (' Two ', ' W ') # Open for writing
Another form of new is three parameters, the second parameter specifies the original permission of the file (often represented as a octal number). The third parameter is a combination of a series of ored flags. The flag is a constant such as file:creat (if the file does not exist) and file: Rdonly (open file as read-only). However, this form is rarely used:
File = File.new ("Three", 0755, file::creat| FILE::WRONLY)
For the sake of operating system and running environment, if you open a file, you must close it. When you open a file for writing, you should do so in order to avoid losing data. The Close method closes a file:
out = File.new ("Captains.log", "W")
# Process as needed ...
Out.close
There is also an open method, the simplest form of which is synonymous with new:
trans = File.Open ("Transactions", "W")
But the open method can also take a block as an argument, and when the block is present, the open file will be passed as a parameter to block. This file will be in the scope of this block, remain open until block ends, automatically shut down:
File.Open ("Somefile", "w") do |file|
file.puts ' line 1 '
file.puts ' line 2 '
file.puts ' third and final line '
end