How to Use File.open in Ruby: Syntax and Examples
Use
File.open in Ruby to open a file by specifying its path and mode (like 'r' for read or 'w' for write). You can provide a block to automatically close the file after use, or handle the file object manually without a block.Syntax
The basic syntax of File.open is:
File.open(filename, mode) do |file| ... end: Opens the file and runs the block, then closes the file automatically.File.open(filename, mode): Opens the file and returns a file object; you must close it manually.
filename is the path to the file, and mode is a string like 'r' (read), 'w' (write), or 'a' (append).
ruby
File.open('example.txt', 'r') do |file| # work with file inside this block end
Example
This example shows how to open a file, write to it, read its contents, and print them. The file is automatically closed after each block finishes.
ruby
File.open('sample.txt', 'w') do |file| file.puts 'Hello, Ruby!' end File.open('sample.txt', 'r') do |file| content = file.read puts content end
Output
Hello, Ruby!
Common Pitfalls
Common mistakes include forgetting to close the file when not using a block, which can cause resource leaks. Also, using the wrong mode can cause errors or overwrite data unintentionally.
Always use a block with File.open when possible to ensure the file closes automatically.
ruby
# Wrong: forgetting to close the file file = File.open('data.txt', 'r') content = file.read # file.close is missing here # Right: using a block to auto-close File.open('data.txt', 'r') do |file| content = file.read end
Quick Reference
| Mode | Description |
|---|---|
| 'r' | Read-only, file must exist |
| 'w' | Write-only, creates or truncates file |
| 'a' | Append, write at end of file or create |
| 'r+' | Read-write, file must exist |
| 'w+' | Read-write, creates or truncates file |
| 'a+' | Read-write, append or create file |
Key Takeaways
Use File.open with a block to automatically close files after use.
Specify the correct mode ('r', 'w', 'a', etc.) to control how the file is accessed.
Always close files manually if you open them without a block to avoid resource leaks.
Use 'r' mode to read existing files and 'w' mode to write or overwrite files.
Appending data requires the 'a' mode to add content without deleting existing data.