How to Read File in Ruby: Simple Syntax and Examples
In Ruby, you can read a file using
File.read('filename') to get the entire content as a string, or use File.open('filename', 'r') with a block to read line by line. These methods let you easily access file contents for processing.Syntax
The basic ways to read a file in Ruby are:
File.read('filename'): Reads the whole file content as a single string.File.open('filename', 'r') do |file| ... end: Opens the file for reading and allows processing line by line inside the block.
Use 'r' mode to open the file for reading.
ruby
content = File.read('example.txt') File.open('example.txt', 'r') do |file| file.each_line do |line| puts line end end
Example
This example shows how to read the entire file content at once and then how to read it line by line.
ruby
File.write('example.txt', "Hello\nWorld\nRuby") # Read whole file content content = File.read('example.txt') puts "Whole content:\n#{content}" # Read file line by line puts "\nReading line by line:" File.open('example.txt', 'r') do |file| file.each_line do |line| puts line.chomp end end
Output
Whole content:
Hello
World
Ruby
Reading line by line:
Hello
World
Ruby
Common Pitfalls
Common mistakes when reading files in Ruby include:
- Not closing the file after opening it without a block, which can cause resource leaks.
- Using
File.readon very large files, which can consume too much memory. - Forgetting to handle exceptions if the file does not exist.
Using a block with File.open automatically closes the file after reading.
ruby
begin # Wrong: opens file but does not close it file = File.open('missing.txt', 'r') puts file.read rescue Errno::ENOENT puts 'File not found!' ensure file.close if file end # Right: using block ensures file is closed begin File.open('missing.txt', 'r') do |file| puts file.read end rescue Errno::ENOENT puts 'File not found!' end
Output
File not found!
Quick Reference
Here is a quick summary of common file reading methods in Ruby:
| Method | Description |
|---|---|
| File.read('filename') | Reads entire file content as a string |
| File.open('filename', 'r') { |f| ... } | Opens file for reading with automatic close |
| file.each_line { |line| ... } | Iterates over each line in the file |
| File.readlines('filename') | Returns an array of all lines in the file |
Key Takeaways
Use File.read('filename') to quickly get all file content as a string.
Use File.open with a block to safely read files line by line and auto-close.
Always handle exceptions for missing files to avoid crashes.
Avoid reading very large files all at once to prevent memory issues.
File.open with a block is the safest and most common pattern for reading files.