From: Devin Mullins Date: 2006-09-28T11:05:52+09:00 Subject: Re: Idiomatic file snarf Eero Saynatkari wrote: > On 2006.09.28 07:02, Tim Bray wrote: >>Currently I have >> f = File.new(fname) >> text = f.read >> f.close > A better way for the above is this: > text = File.open(file_name) {|f| f.read} To expand on that: the form that takes a block automatically calls f.close when the block is done. What's more, it does it in an *ensure clause*, you scr1pt k1ddie. Also, Kernel#open exists. So: text = open(file_name) {|f| f.read} What's more, if you're dealing with files on a linely basis, File.include? Enumerable, so you can do fun things like: matches = open(file_name) {|f| f.grep(/juicy stuff/)} To return an Array of matching lines without having to bring the whole file into memory. (Though, if you don't care about memory, File.readlines(file_name).grep /juicy stuff/ is prettier.) Devin