[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Idiomatic file snarf

Tim Bray

9/27/2006 10:02:00 PM

I want to open a file, suck the contexts into a variable and close it
again. I suppose I could IO#each and glue the lines together.

Currently I have

f = File.new(fname)
text = f.read
f.close

Surely there's an idiomatic Ruby one-liner? I must be looking in the
wrong place @ruby-doc.org -Tim



6 Answers

James Gray

9/27/2006 10:07:00 PM

0

On Sep 27, 2006, at 5:02 PM, Tim Bray wrote:

> I want to open a file, suck the contexts into a variable and close
> it again. I suppose I could IO#each and glue the lines together.
>
> Currently I have
>
> f = File.new(fname)
> text = f.read
> f.close
>
> Surely there's an idiomatic Ruby one-liner?

Sure:

text = File.read(fname)

James Edward Gray II



Thomas Adam

9/27/2006 10:09:00 PM

0

On Thu, 28 Sep 2006 07:02:13 +0900 Tim Bray <tbray@textuality.com>
wrote:

> I want to open a file, suck the contexts into a variable and close
> it again. I suppose I could IO#each and glue the lines together.
>
> Currently I have
>
> f = File.new(fname)
> text = f.read
> f.close
>
> Surely there's an idiomatic Ruby one-liner? I must be looking in
> the wrong place @ruby-doc.org -Tim

some_variable = File.new(fname).readlines

-- Thomas Adam

--
"If I were a witch's hat, sitting on her head like a paraffin stove, I'd
fly away and be a bat." -- Incredible String Band.

Eero Saynatkari

9/27/2006 10:32:00 PM

0

On 2006.09.28 07:02, Tim Bray wrote:
> I want to open a file, suck the contexts into a variable and close it
> again. I suppose I could IO#each and glue the lines together.

The 'correct' way is:

text = File.read file_name

> 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}

John Carter

9/27/2006 11:40:00 PM

0

Devin Mullins

9/28/2006 2:06:00 AM

0

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

John Carter

9/28/2006 3:32:00 AM

0