開啟和關閉檔案
手動開啟和關閉檔案。
# 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