0
0
RubyHow-ToBeginner · 3 min read

How to Use File.read in Ruby: Simple Guide with Examples

In Ruby, use File.read to read the entire content of a file as a string by passing the file path as an argument. It returns the file content or raises an error if the file does not exist.
📐

Syntax

The File.read method reads the whole content of a file and returns it as a string.

  • File.read(path, [length], [offset])
  • path: The file path as a string.
  • length (optional): Number of bytes to read.
  • offset (optional): Position in the file to start reading from.
ruby
content = File.read("example.txt")
puts content
💻

Example

This example shows how to read the entire content of a file named example.txt and print it.

ruby
File.write("example.txt", "Hello, Ruby File.read!\nThis is a test file.")

content = File.read("example.txt")
puts content
Output
Hello, Ruby File.read! This is a test file.
⚠️

Common Pitfalls

Common mistakes include:

  • Trying to read a file that does not exist, which raises an Errno::ENOENT error.
  • Not handling exceptions when the file is missing or unreadable.
  • Assuming File.read reads line by line; it reads the whole file at once.

Always ensure the file path is correct and consider using begin-rescue to handle errors.

ruby
begin
  content = File.read("missing.txt")
  puts content
rescue Errno::ENOENT
  puts "File not found!"
end
Output
File not found!
📊

Quick Reference

MethodDescription
File.read(path)Reads entire file content as a string.
File.read(path, length)Reads specified number of bytes from start.
File.read(path, length, offset)Reads bytes starting from offset.
Raises Errno::ENOENTIf file does not exist.

Key Takeaways

Use File.read with the file path to get the whole file content as a string.
File.read raises an error if the file does not exist, so handle exceptions.
You can optionally specify how many bytes to read and where to start.
File.read reads the entire file at once, not line by line.
Always verify the file path and permissions before reading.