Domanda

As per my concept when a file is opened using

infile = File.open(fname)

It can/should be closed only when I do

infile.close

Now I tried following on rails console

infile.each do |line|
puts line
end

Next time i tried to do the same I got no output. However if i do infile = File.open(fname) again the above code starts giving the right output (only for 1 subsequent try).

What am I missing here? Is the file getting closed? or the file pointer is pointing to the end (but again as per my concepts .each should take care of that)

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top