Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Ruby Index

📁 File & IO — File reading, writing, and directory operations

Ruby file I/O uses blocks that auto-close handles (RAII pattern). Three-argument open prevents injection attacks.

📋 Methods & Functions

NameSignatureDescription
File.readFile.read(path) → StringRead entire file as string
File.readlinesFile.readlines(path) → ArrayRead file as array of lines
File.writeFile.write(path, content) → IntegerWrite string to file
File.openFile.open(path, mode) {|f| block}Open file with block (auto-close)
File.exist?File.exist?(path) → boolTrue if path exists
File.directory?File.directory?(path) → boolTrue if path is directory
File.sizeFile.size(path) → IntegerReturn file size in bytes
File.deleteFile.delete(path) → IntegerDelete file
File.renameFile.rename(old, new) → 0Rename / move file
File.basenameFile.basename(path, ext) → StringReturn filename part
File.dirnameFile.dirname(path) → StringReturn directory part
File.extnameFile.extname(path) → StringReturn extension (.txt etc.)
File.joinFile.join(*parts) → StringJoin path components
File.expand_pathFile.expand_path(path) → StringReturn absolute path
Dir.mkdirDir.mkdir(path) → 0Create directory
Dir.globDir.glob(pattern) → ArrayReturn files matching pattern
Dir.pwdDir.pwd → StringReturn current working directory
IO.foreachIO.foreach(path) {|line| block}Iterate file lines without loading all
IO.readlinesIO.readlines(path) → ArrayRead all lines
IO.writeIO.write(path, str) → IntegerWrite string to file
puts/printputs(obj) / print(obj)Write to stdout with/without newline
getsgets → StringRead one line from stdin
STDIN/STDOUTIO objectsStandard input/output streams
requirerequire 'csv'Load standard or gem library
StringIOrequire 'stringio'; StringIO.new(str)In-memory IO stream

💡 Example Program

Run with ruby script.rb.

require "tmpdir"

# Write a file
File.write("students.txt", <<~DATA)
  Alice 95
  Bob   87
  Carol 92
  Dave  78
DATA

# Read entire file
puts File.read("students.txt")

# Iterate lines without loading all into memory
IO.foreach("students.txt") do |line|
  name, score = line.split
  puts "#{name} => #{score.to_i >= 90 ? "A" : "B"}" if name
end

# Open with block (auto-close)
File.open("students.txt", "a") { |f| f.puts "Eve   98" }

# readlines + processing
top = File.readlines("students.txt")
       .map { |l| l.split }
       .select { |parts| parts.size == 2 && parts[1].to_i >= 90 }
       .map { |name, score| "#{name}(#{score})" }
puts "Top students: #{top.join(", ")}"

# File metadata
puts "Size: #{File.size("students.txt")} bytes"
puts "Basename: #{File.basename("students.txt", ".txt")}"
puts "Absolute: #{File.expand_path("students.txt")}"

# Dir.glob
puts Dir.glob("*.txt").inspect

File.delete("students.txt")
puts "Done."
# ruby file_demo.rb

← Hash  |  🏠 Index  |  Enumerable →