Kernel#open
open(path, mode="r") -> file or io Returns:
File or IO · Updated March 13, 2026 · Kernel Methods files io reading writing pipes
The open method is versatile, opening files for reading/writing and also creating IO pipes for command execution. It’s a core method for file and process interaction.
Opening Files
# Read mode (default)
file = open("data.txt")
content = file.read
file.close
# Block form (auto-closes)
open("data.txt") { |f| f.read }
File Modes
# Various modes
open("file.txt", "r") # Read
open("file.txt", "w") # Write (truncates)
open("file.txt", "a") # Append
open("file.txt", "r+") # Read/write
open("file.txt", "w+") # Read/write (truncates)
open("file.txt", "a+") # Read/append
Command Execution with Pipes
# Read output from command
output = open("|ls -la") { |p| p.read }
puts output
# Write to command
open("|tr a-z A-Z", "w") { |p| p.puts "hello world" }
Practical Examples
Reading Files
# Line by line
open("file.txt") do |f|
f.each_line { |line| puts line }
end
# All content
content = open("file.txt", &:read)
Writing Files
# Write data
open("output.txt", "w") do |f|
f.puts "Hello"
f.puts "World"
end
# Append to file
open("log.txt", "a") do |f|
f.puts "#{Time.now}: Log entry"
end
Processing CSV
# Simple CSV reading
open("data.csv", "r") do |f|
f.each_line do |line|
fields = line.chomp.split(",")
# Process fields
end
end
Network-like Operations
# Reading from URL (with open-uri)
require 'open-uri'
open("https://example.com") { |f| puts f.read }
Binary Files
# Read binary data
open("image.png", "rb") do |f|
data = f.read
# Process binary
end
# Write binary
open("output.bin", "wb") do |f|
f.write(bytes)
end
With Encoding
# Specify encoding
open("file.txt", "r:UTF-8") { |f| f.read }
open("file.txt", "r:UTF-16LE:UTF-8") { |f| f.read }
Error Handling
begin
file = open("missing.txt")
# Process
rescue Errno::ENOENT => e
puts "File not found: #{e.message}"
ensure
file.close if file
end
The open method is fundamental to Ruby’s IO system, supporting everything from simple file operations to complex pipe-based inter-process communication.