in a ruby learning book .I face this code :
f = File.new("a.txt", "r")
while a = f.getc
puts a.chr
f.seek(5, IO::SEEK_CUR)
end
author writes that this code produce every fifth character in a file, but I don’t understand why? please explain me line by line.
thanks.
This line opens the file in read mode and keeps the file object(as an I/O(Input/Output) stream) in variable f. (See File#new)
getcis a method of class IO which gets one character of the I/O stream at a time and it will givenil, when it meets the end of the I/O stream. Sowhile a = f.getcwill loop until the end of file. (See IO#getc)f.getcwill give the ASCII value of the character and inorder to get the character from the ASCII value, we applya.chr(See Integer#chr). I think in Ruby 1.9, we will get the character itself as the output ofgetc, but for earlier versions, we get the ASCII value as the output. The firstgetccommand reads the first character and moves the position of I/O stream after the first character.seekis a method of I/O stream which changes the position of the I/O stream by an offset of the first parameter from the second parameter.IO::SEEK_CURis a constant which gives the current position of the I/O stream. Sof.seek(5, IO::SEEK_CUR)moves the position to 5 places from the current position. (See IO#seek)This will continue till
a = f.getcbecomes a false condition(here at the end of file,f.getcbecomesnil, which is a falsey value in Ruby(falseandnilare the only falsy values in Ruby, all others are truth values))Use IRB to study and experiment with Ruby.