This is a summary of the modes for the File.open method, which frequently appears in the Ruby Silver exam.
| Mode | Description |
|---|---|
| “r” | Read mode. This is the default if no argument is specified. |
| “w” | Write mode. If the file exists, its contents are cleared. |
| “a” | Append mode. Always appends to the end of the file. |
| “r+” | Read-write mode. The read/write position starts at the beginning. |
| “w+” | Read-write mode. Similar to r+, but clears the file contents if it exists. |
| “a+” | Read-write mode. The read position starts at the beginning, but writes always append to the end. |
<!-- Sample file: sample.md -->
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.
r and r+rRead mode. This is the default if no argument is specified.
file = File.open("sample.md") # "r" is the default, so it can be omitted
puts file.read
file.close
=>
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.
r+Read-write mode. The read/write position starts at the beginning.
file = File.open("sample.md", "r+")
file.puts("My Diary")
file.close
=>
My Diary
An open-source dynamic programming language focused on simplicity and productivity.
w and w+wWrite mode. If the file exists, its contents are cleared.
file = File.open("sample.md", "w")
file.puts("My Diary")
file.close
=>
My Diary
w+Read-write mode. Similar to r+, but clears the file contents if it exists.
file = File.open("sample.md", "w+")
file.puts("My Diary")
file.close
=>
My Diary
a and a+aAppend mode. Always appends to the end of the file.
file = File.open("sample.md", "a")
file.puts("My Diary")
file.close
=>
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.
My Diary
a+Read-write mode. The read position starts at the beginning, but writes always append to the end.
file = File.open("sample.md", "a+")
file.puts("My Diary")
file.close
=>
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.
My Diary