0
0
RubyHow-ToBeginner · 3 min read

How to Write a File in Ruby: Simple Syntax and Examples

In Ruby, you can write to a file using File.open with the write mode 'w' and a block to handle the file. Inside the block, use write or puts to add content. This ensures the file is properly closed after writing.
📐

Syntax

The basic syntax to write to a file in Ruby uses File.open with a mode and a block. The mode 'w' means write mode, which creates the file or overwrites it if it exists. Inside the block, you use write or puts to add text to the file. The file is automatically closed when the block ends.

ruby
File.open('filename.txt', 'w') do |file|
  file.write("Hello, world!\n")
end
💻

Example

This example creates a file named greeting.txt and writes a friendly message inside. It shows how to open the file, write text, and close it automatically.

ruby
File.open('greeting.txt', 'w') do |file|
  file.puts("Hello from Ruby!")
  file.puts("Writing files is easy.")
end

puts "File written successfully."
Output
File written successfully.
⚠️

Common Pitfalls

One common mistake is forgetting to close the file, which can cause data loss or file locks. Using File.open with a block avoids this by closing the file automatically. Another pitfall is using the wrong mode, like 'r' (read) instead of 'w' (write), which will cause errors when trying to write.

ruby
wrong_way = <<-RUBY
file = File.open('test.txt', 'r')
file.write('This will fail')
file.close
RUBY

right_way = <<-RUBY
File.open('test.txt', 'w') do |file|
  file.write('This works!')
end
RUBY
📊

Quick Reference

ActionCode ExampleDescription
Open file for writingFile.open('file.txt', 'w')Creates or overwrites a file for writing
Write textfile.write('text')Writes string without newline
Write linefile.puts('text')Writes string with newline
Close filefile.closeCloses file (automatic with block)

Key Takeaways

Use File.open with 'w' mode and a block to write files safely in Ruby.
Inside the block, use write or puts to add content to the file.
The block ensures the file is closed automatically to prevent errors.
Avoid using read mode 'r' when writing files to prevent exceptions.
Use puts to add a newline automatically, write to add raw text.