Devin Mullins
9/28/2006 2:06:00 AM
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