打开和关闭文件
手动打开和关闭文件。
# 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
使用块自动关闭文件。
f = File.open("test.txt", "r") do |f|
# do something with file f
puts f.read # for example, read it
end