0
0
Rubyprogramming~5 mins

Why file handling matters in Ruby

Choose your learning style9 modes available
Introduction

File handling lets your program save and read information from files. This helps keep data safe even after the program stops.

Saving user settings so they stay the same next time you open the app.
Reading a list of names or data from a file to use in your program.
Writing logs to track what your program did during its run.
Storing scores or progress in a game so players can continue later.
Syntax
Ruby
File.open('filename', 'mode') do |file|
  # read or write using file
end
Use 'r' mode to read, 'w' to write (overwrite), and 'a' to add (append) to a file.
The block ensures the file closes automatically after use.
Examples
This writes 'Hello, world!' to example.txt, creating or replacing the file.
Ruby
File.open('example.txt', 'w') do |file|
  file.puts 'Hello, world!'
end
This reads all content from example.txt and prints it.
Ruby
File.open('example.txt', 'r') do |file|
  content = file.read
  puts content
end
Sample Program

This program writes a greeting to a file, then reads and prints it.

Ruby
File.open('greeting.txt', 'w') do |file|
  file.puts 'Hi there!'
end

File.open('greeting.txt', 'r') do |file|
  puts file.read
end
OutputSuccess
Important Notes

Always close files or use blocks to avoid errors and free resources.

File modes control if you read, write, or add to files.

Summary

File handling saves and loads data outside your program.

Use different modes to read or write files safely.

Blocks help manage files by closing them automatically.