Stefano Crocco
6/4/2008 5:27:00 PM
On Wednesday 04 June 2008, Justin To wrote:
> report =3D File.open('ReportTxt.txt', 'r') do |L|
> =C2=A0 =C2=A0while line =3D L.gets
>
> =C2=A0 report.getc.chr
>
> =C2=A0 =C2=A0 end
> end
There are at least two problems with your code:
1) you use the variable report in the block, but the variable is assigned a=
=20
value *after* the File.open method returns. This means that when you call=20
report.getc inside your block, report is nil, hence the error you're gettin=
g=20
(by the way, when you ask for help, you should specify what kind of error=20
you're getting).
2) You use L.gets to iterate. But: a) gets, with no argument, iterates=20
linewise, which means you'll read a character for each line; b) gets moves =
the=20
position in the file, which means that, after L.gets reads the last line of=
=20
the file, you'll get an error.
To achieve what you want, you can use the following code (by the way, capit=
al=20
letters in ruby are used for constants, so it's better not to use them for=
=20
block variables):
=46ile.open('ReportTxt.txt', 'r') do |f|
until f.eof?
f.getc.chr
end
end
I hope this helps
Stefano