Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   When file gets closed in a block (http://www.velocityreviews.com/forums/t841680-when-file-gets-closed-in-a-block.html)

Damjan Rems 06-19-2007 09:11 AM

When file gets closed in a block
 

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

--
Posted via http://www.ruby-forum.com/.


Sascha Abel 06-19-2007 09:24 AM

Re: When file gets closed in a block
 
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

--
Posted via http://www.ruby-forum.com/.


Damjan Rems 06-19-2007 09:52 AM

Re: When file gets closed in a block
 
>
> 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

--
Posted via http://www.ruby-forum.com/.


Rob Biedenharn 06-19-2007 02:10 PM

Re: When file gets closed in a block
 
On Jun 19, 2007, at 5:52 AM, Damjan Rems wrote:
>> 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


Close, try it like this:

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

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com






All times are GMT. The time now is 10:26 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.