When file gets closed in a block

D

Damjan Rems

I like to use this a lot:
File.new(cName,'wb+').write('aText')

I have understood that file gets automaticly closed. But when? You can
not delete file right after above statement. If you want to delete file
you must use this.
f = File.new(cName,'wb+')
f.write(attachment.unpack('m'))
f.close

When does the file in block gets closed.

by
TheR
 
S

Sascha Abel

If you open a file with File#new, you have to close it yourself by
calling File#close.

---
f = File.new('someFilename', 'w')
f.write(text1)
f.write(text2)
f.close
---

You can write as often as you like to f as long as you don't close it.

File#open closes the file automatically if passed a block:

---
File.open('someFilename', 'w') {|f|
f.write(text1)
f.write(text2)
}
---

Without a block File#open ist just an alias for File#new.


Sascha
 
D

Damjan Rems

You can write as often as you like to f as long as you don't close it.

File#open closes the file automatically if passed a block:

---
File.open('someFilename', 'w') {|f|
f.write(text1)
f.write(text2)
}

I guess then my one liner should look like this:

File.new(cName,'wb+') { |f|.write('aText') }

by
TheR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top