Introduction
File handling lets your program save and read information from files. This helps keep data safe even after the program stops.
File handling lets your program save and read information from files. This helps keep data safe even after the program stops.
File.open('filename', 'mode') do |file| # read or write using file end
File.open('example.txt', 'w') do |file| file.puts 'Hello, world!' end
File.open('example.txt', 'r') do |file| content = file.read puts content end
This program writes a greeting to a file, then reads and prints it.
File.open('greeting.txt', 'w') do |file| file.puts 'Hi there!' end File.open('greeting.txt', 'r') do |file| puts file.read end
Always close files or use blocks to avoid errors and free resources.
File modes control if you read, write, or add to files.
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.
File.open('test.txt', 'w') { |f| f.puts 'Line 1' }
content = File.read('test.txt')
puts contentfile = File.open('data.txt', 'r')
file.puts 'Hello'
file.closePass the test and this pattern moves unknown