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:
  1. Use close (remembering to catch exceptions).
    f = open "file"
    begin
      f.each {|l| print l}
    ensure
      f.close
    end
    
  2. Use the block form of open
    File.open("file") do |f|
      f.readlines.each { |l| print l }
    end
    
  3. Use foreach
    IO.foreach("file") {|l| print l}
    
  4. Use readlines.
    IO.readlines("file").each {|l| print l}
    

Labels:


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?