IOError
RubyERRORNotableIO

IO operation failed on closed or invalid stream

Quick Answer

Ensure IO objects are open before reading/writing; use File.open with a block to guarantee automatic closing.

What this means

Raised when an IO operation is performed on a closed or invalid stream. It is the parent of EOFError. Distinct from Errno::* errors which cover OS-level IO failures.

Why it happens
  1. 1Reading from or writing to a file that has already been closed
  2. 2Writing to a read-only stream

Fix

Use File.open with a block

Use File.open with a block
File.open('data.txt', 'r') do |f|
  contents = f.read
end
# file is automatically closed after the block, no risk of IOError on re-use

Why this works

The block form ensures the file is closed at block exit; the reference becomes inaccessible outside.

Code examples
Writing to closed IOruby
f = File.open('out.txt', 'w')
f.close
f.write('oops')
# IOError: closed stream
Block form avoids the issueruby
File.open('out.txt', 'w') { |f| f.write('safe') }
Rescue IOErrorruby
begin
  io.write(data)
rescue IOError => e
  puts "Stream error: #{e.message}"
end
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors