Simple IO question

This prints every fifth character in a file:

f = File.new(“test.txt”, “r”)
while a = f.getc
puts a.chr
f.seek(5, IO::SEEK_CUR)
end

I don’t quite get the meaning of it. Is it like, “while the variable
‘a’ has a value or contains something, it should be printed onto the
screen”?

Why is it not “while a == f.getc” ? ( == instead of = )

What does getc here mean anyway? I know it reads a single character,
correct?

Thank you guys!

On Thu, May 24, 2012 at 10:34 AM, Kaye Ng [email protected] wrote:

screen"?

Why is it not “while a == f.getc” ? ( == instead of = )

What does getc here mean anyway? I know it reads a single character,
correct?

a = f.getc assigns to the variable a the next character from the file
f. You need to know also, that f.getc will return nil when the end of
file is reached. The assignment returns the assigned value as the
result of the expression. This code uses this value as the condition
of the while. So it keeps reading a char from the file and assigning
to variable a, until f.getc returns nil, at which point a gets
assigned nil, the expression returns nil, the while condition is not
met and the loop ends.

Jesus.

f.getc will return nil when there is no char more.
so,
“a = f.getc” is have two roles

  1. assign value to a
  2. check end of file

2012/5/24 Kaye Ng [email protected]

screen"?