Monday, September 24, 2007
File I/O in Ruby
Ruby FAQ which seems to constantly move around and is currently not available (Google cache is though) has a very useful section 10.6 Should I feel uneasy if I don't close a file :
There are at least four good ways of ensuring that you do close a file:
- Use close (remembering to catch exceptions).
f = open "file" begin f.each {|l| print l} ensure f.close end- Use the block form of open
File.open("file") do |f| f.readlines.each { |l| print l } end- Use foreach
IO.foreach("file") {|l| print l}- Use readlines.
IO.readlines("file").each {|l| print l}
Labels: ruby