Reputation: 3435
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.
Upvotes: 0
Views: 98
Reputation: 17803
f = File.new("a.txt", "r")
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)
while a = f.getc
getc
is a method of class IO which gets one character of the I/O stream at a time and it will give nil
, when it meets the end of the I/O stream. So while a = f.getc
will loop until the end of file. (See IO#getc)
puts a.chr
f.getc
will give the ASCII value of the character and inorder to get the character from the ASCII value, we apply a.chr
(See Integer#chr). I think in Ruby 1.9, we will get the character itself as the output of getc
, but for earlier versions, we get the ASCII value as the output. The first getc
command reads the first character and moves the position of I/O stream after the first character.
f.seek(5, IO::SEEK_CUR)
seek
is 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_CUR
is a constant which gives the current position of the I/O stream. So f.seek(5, IO::SEEK_CUR)
moves the position to 5 places from the current position. (See IO#seek)
This will continue till a = f.getc
becomes a false condition(here at the end of file, f.getc
becomes nil
, which is a falsey value in Ruby(false
and nil
are the only falsy values in Ruby, all others are truth values))
Use IRB to study and experiment with Ruby.
Upvotes: 3
Reputation: 118751
a = f.getc; puts a.chr
outputs a single character; f.seek(5, IO::SEEK_CUR)
moves forward by 5 characters.
Upvotes: 1