[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

File I/O

name pipe

11/1/2006 1:51:00 PM

Hello,

I have some text to be written to a file.
After receiving data from webrick server I modify it lil bit and then
write it to a file.

fd = File.open("file.txt", "w")
fd.puts "#{data}"

The code doesnt give error and runs successfully however file.txt
doesnt contain any data.
Just puts "#{data}" gives a give output on console. Means its not empty.

Can anyone tell me why does it happen ?

3 Answers

Peter Szinek

11/1/2006 1:55:00 PM

0

name pipe wrote:
> Hello,
>
> I have some text to be written to a file.
> After receiving data from webrick server I modify it lil bit and then
> write it to a file.
>
> fd = File.open("file.txt", "w")
You can use

open("file.txt", "w")

as well.

> fd.puts "#{data}"
Why not just

fd.puts data

as for the empty file problem, maybe try to close fd:

fd.close

Peter
http://www.rubyra...


Ross Bamford

11/1/2006 2:01:00 PM

0

On Wed, 01 Nov 2006 13:50:49 -0000, name pipe <namepipe@gmail.com> wrote=
:

> Hello,
>
> I have some text to be written to a file.
> After receiving data from webrick server I modify it lil bit and then
> write it to a file.
>
> fd =3D File.open("file.txt", "w")
> fd.puts "#{data}"
>
> The code doesnt give error and runs successfully however file.txt
> doesnt contain any data.
> Just puts "#{data}" gives a give output on console. Means its not empt=
y.
>
> Can anyone tell me why does it happen ?
>

You're never closing the file, which is why it's empty (your writes are =
=

never flushed).
Try either fd.close at the end, or (better IMHO) use the block form:

File.open("file.txt", "w") do |fd|
fd.puts "#{data}" # or fd.puts data.to_s
end

Hope that helps.
-- =

Ross Bamford - rosco@roscopeco.remove.co.uk

Jeremy McAnally

11/1/2006 2:04:00 PM

0

Hello,
That works, or, even more Rubytastic:

open("file.txt", "w") do |fd|
fd.puts data
end

Using the block automatically closes the file. :)

--Jeremy

On 11/1/06, Peter Szinek <peter@rubyrailways.com> wrote:
> name pipe wrote:
> > Hello,
> >
> > I have some text to be written to a file.
> > After receiving data from webrick server I modify it lil bit and then
> > write it to a file.
> >
> > fd = File.open("file.txt", "w")
> You can use
>
> open("file.txt", "w")
>
> as well.
>
> > fd.puts "#{data}"
> Why not just
>
> fd.puts data
>
> as for the empty file problem, maybe try to close fd:
>
> fd.close
>
> Peter
> http://www.rubyra...
>
>
>