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
- 1Reading from or writing to a file that has already been closed
- 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-useWhy 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 streamBlock 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}"
endSame error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev