Opening and closing a file
suggest changeOpen a file, then close it. Each assignment replaces f, so close the file before you open another.
# Using new method
f = File.new("test.txt", "r") # reading
f = File.new("test.txt", "w") # writing
f = File.new("test.txt", "a") # appending
# Using open method
f = open("test.txt", "r")
# Remember to close files
f.close
The block form closes the file when the block ends. File.open returns the block's value, not the file.
f = File.open("test.txt", "r") do |f|
# do something with file f
puts f.read # for example, read it
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents