Ruby file I/O uses blocks that auto-close handles (RAII pattern). Three-argument open prevents injection attacks.
| Name | Signature | Description |
|---|---|---|
| File.read | File.read(path) → String | Read entire file as string |
| File.readlines | File.readlines(path) → Array | Read file as array of lines |
| File.write | File.write(path, content) → Integer | Write string to file |
| File.open | File.open(path, mode) {|f| block} | Open file with block (auto-close) |
| File.exist? | File.exist?(path) → bool | True if path exists |
| File.directory? | File.directory?(path) → bool | True if path is directory |
| File.size | File.size(path) → Integer | Return file size in bytes |
| File.delete | File.delete(path) → Integer | Delete file |
| File.rename | File.rename(old, new) → 0 | Rename / move file |
| File.basename | File.basename(path, ext) → String | Return filename part |
| File.dirname | File.dirname(path) → String | Return directory part |
| File.extname | File.extname(path) → String | Return extension (.txt etc.) |
| File.join | File.join(*parts) → String | Join path components |
| File.expand_path | File.expand_path(path) → String | Return absolute path |
| Dir.mkdir | Dir.mkdir(path) → 0 | Create directory |
| Dir.glob | Dir.glob(pattern) → Array | Return files matching pattern |
| Dir.pwd | Dir.pwd → String | Return current working directory |
| IO.foreach | IO.foreach(path) {|line| block} | Iterate file lines without loading all |
| IO.readlines | IO.readlines(path) → Array | Read all lines |
| IO.write | IO.write(path, str) → Integer | Write string to file |
| puts/print | puts(obj) / print(obj) | Write to stdout with/without newline |
| gets | gets → String | Read one line from stdin |
| STDIN/STDOUT | IO objects | Standard input/output streams |
| require | require 'csv' | Load standard or gem library |
| StringIO | require 'stringio'; StringIO.new(str) | In-memory IO stream |
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