open(file[, mode]) {|io| ... }
Opens file and returns a File object. mode specifies one of the following strings. When mode is omitted, the default is "r".
- "r": Opens file in read mode.
- "w": Opens file in write mode. If a file already exists when file is opened, the previous file's contents will be deleted.
- "a": Opens file in write mode. Output will always be appended to the end of the file.
Using "+" opens the file in read-write mode (RDWR):
- "r+": Sets the read-write position to the beginning of the file.
- "w+": The same as "r+", but if a file already exists when file is opened, the previous file's contents will be deleted.
- "a+": The same as "r+", but if a file already exists when file is opened, the read-write position will be set to the end of the file.
The "b" flag can also be added to any of these (in the format "r+b") to open the file in binary mode.
When open is called along with a block, it opens the file, executes the block, then closes the file when execution is complete. In this case, returns the result of the block evaluation. That is:
open(path, mode) do |f|
  ...
end
Â
# almost identical to the above
f = open(path, mode)
begin
  ...
ensure
 f.close
end