How to Use File.write in Ruby: Simple Guide
In Ruby, use
File.write(filename, content) to create or overwrite a file with the given content. This method writes the string directly to the file and returns the number of bytes written.Syntax
The File.write method takes two main arguments: the filename as a string and the content you want to write to the file. It overwrites the file if it exists or creates a new one if it doesn't.
filename: The name or path of the file to write to.content: The string data to write inside the file.
ruby
File.write("example.txt", "Hello, Ruby!")
Example
This example shows how to write a simple greeting message to a file named greeting.txt. After running, the file will contain the text "Hello, Ruby!".
ruby
filename = "greeting.txt" content = "Hello, Ruby!" bytes_written = File.write(filename, content) puts "Wrote #{bytes_written} bytes to #{filename}."
Output
Wrote 12 bytes to greeting.txt.
Common Pitfalls
Common mistakes when using File.write include:
- Not having write permission for the file or directory, causing errors.
- Expecting
File.writeto append content instead of overwriting. - Passing non-string content without converting it to a string first.
Always ensure you have permission and convert data to string if needed.
ruby
wrong_content = 12345 # This will NOT raise an error because File.write converts content to string internally File.write("number.txt", wrong_content) # Explicit conversion is also fine File.write("number.txt", wrong_content.to_s)
Quick Reference
| Method | Description |
|---|---|
| File.write(filename, content) | Writes content to filename, overwriting if exists. |
| File.write(filename, content, mode: "a") | Appends content to filename (using mode option). |
| File.write(filename, content.to_s) | Ensures content is string before writing. |
Key Takeaways
Use File.write(filename, content) to quickly write or overwrite files in Ruby.
File.write returns the number of bytes written to the file.
Make sure content is a string or convert it before writing.
File.write overwrites existing files; use append mode if needed.
Check file permissions to avoid write errors.