File Access

Opening files

myFile = File.new(filename, mode)
myFile = File.open(filename, mode)

File.open (filename, mode) do |myFile|
...
end
mode: [r, r+, w, w+, a, a+][b]   (default: r)
r read-only (default)
r+ read-write
w write-only (existing file erased)
w+ read-write (existing file erased)
a write-only (starts at end of existing file)
a+ read-write (starts at end of existing file)
b binary mode (for portability to DOS/Windows)

Reading files

# Read the next line
myFile.gets

# Read each character
myFile.each_byte do |ch|
...
end

# Read each line
myFile.each_line do |line|
...
end

# Read each line
IO.foreach("filename") do |line|
...
end

# Read the entire file into an array
myArray = IO.readlines("filename")

Writing files

myFile.puts expr     # Adds a newline
myFile.print expr # Does not add a newline

File position

integer = fileobject.pos
integer = fileobject.tell # Synonym for pos
  • Gets the current file position, in bytes (0-based)
fileobject.rewind
  • Move the file position to the beginning of the file
fileobject.seek(offset, relative_to)
relative_to: [IO::SEEK_SET, IO::SEEK_CUR, IO::SEEK_END]   (default: IO::SEEK_SET)
IO::SEEK_SET Beginning of the file
IO::SEEK_CUR Current file position
IO::SEEK_END End of the file
  • Changes the file position

Closing files

myFile.close