From: Chris Gernon Date: 2007-01-31T02:50:00+09:00 Subject: Re: Correct way to process a file in Ruby? Dave Hatton wrote: > What is the correct way to code the following in Ruby? > > open file > read field from file > determine from field the type of file > case file type in > type 1) do this (lots of stuff) > type 2) do that (even more stuff) > type 3) do something else (you get the picture) > *) error > esac > close file You shouldn't need to open/close the file more than once. Unless I'm misunderstanding something, you should be able to just do something like this: File.open('huge.txt') do |file| first_line = file.gets file_type = determine_file_type(first_line) case file_type when 'csv': process_csv(file) when 'tab_delimited': process_tab(file) else puts "Error! OMG!" end end def process_csv(file) file.each do |line| # do something with the line end end The main File.open block handles the opening and closing of the file, and you just pass the file handle to the methods that do the actual processing. Nice and simple. -- Posted via http://www.ruby-forum.com/.