As I understand, this is what are you trying:
infile = File.open(fname)
infile.each do |line|
puts line
end #=> Prints the lines
infile.each do |line|
puts line
end #=> Prints nothing
infile.close
This happens because iterating on an IO instance keeps the pointer of the line you are reading; I guess for POSIX conformity, which is mirrored in the Ruby interpreter implementation (which is plain C), and thus in Ruby API.
When you run an instruction which resets the line pointer, like closing and reopening the file, the pointer will be again at the beginning of the file, and each
will iterate from the beginning of the file.
If you want to reiterate you can rewind
the IO pointer:
infile = File.open(fname)
infile.each do |line|
puts line
end #=> Prints the lines
infile.rewind
infile.each do |line|
puts line
end #=> Prints the lines
infile.close
Or use IO#reopen
:
infile = File.open(fname)
infile.each do |line|
puts line
end #=> Prints the lines
infile.reopen File.open(fname)
infile.each do |line|
puts line
end #=> Prints the lines
infile.close
Or close the file and create another instance:
infile = File.open(fname)
infile.each do |line|
puts line
end #=> Prints the lines
infile.close
infile = File.open(fname)
infile.each do |line|
puts line
end #=> Prints the lines
infile.close