File.open auto-close

I know opening a file and passing a block will execute the block in
context
of the file and then close the file.

Example:

File.open(“somefile.txt”) {|f| the_text = f.read }

After running, somefile.txt will be closed.

I’m wondering if it’s ok to read a file like this:

the_text = File.open(“somefile.txt”).read

Will that close automatically? If not, how would I go about closing it?

Thanks,
Sam

No, file won’t be closed (you didn’t pass block) and you can’t do it
because you don’t have reference to file (lost when chaining).
But there is class method File.read so you can:

the_text = File.read(“somefile.txt”)

:slight_smile:


Rados³aw Bu³at

http://radarek.jogger.pl - mój blog

It’s even easier :slight_smile: Try

the_text = File.read(“somefile.txt”)

2008/5/29 RadosÅ‚aw BuÅ‚at [email protected]:

No, file won’t be closed (you didn’t pass block) and you can’t do it
because you don’t have reference to file (lost when chaining).
But there is class method File.read so you can:

the_text = File.read(“somefile.txt”)

Duhhhh. I’m a moron. I never thought of that.

Thanks.

Incidentally, I notice the docs on ruby-doc are still broken for File
class,
which is the first place I tried to look. =)

Thanks again.

Sam