CodeToLive

File Handling in Ruby

Ruby provides simple and intuitive methods for file handling using the File class.

Reading a File

Use the File.read method to read the contents of a file.


content = File.read("example.txt")
puts content
      

Writing to a File

Use the File.write method to write data to a file.


File.write("example.txt", "Hello, Ruby!")
      

Appending to a File

Use the File.open method with the append mode to add data to a file.


File.open("example.txt", "a") do |file|
  file.puts "Appending this line!"
end
      

File Modes

Ruby supports various file modes for different operations:

Reading Line by Line

Use File.foreach to read a file line by line.


File.foreach("example.txt") do |line|
  puts line
end
      

File Metadata

Ruby provides methods to access file metadata, such as size, modification time, and file type.


puts "File size: #{File.size("example.txt")} bytes"
puts "Last modified: #{File.mtime("example.txt")}"
puts "Is a directory? #{File.directory?("example.txt")}"
      

Error Handling

Always handle errors when working with files to avoid crashes.


begin
  File.open("nonexistent_file.txt") do |file|
    puts file.read
  end
rescue Errno::ENOENT => e
  puts "File not found: #{e.message}"
end
      

Best Practices

Next: Error Handling in Ruby