One of the Ruby way IO

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.