because as each iterates through the file it "consumes" the file contents (well, it remembers how far it has got.) You can usually rewind a file to the beginning, so:
because as each iterates through the file it "consumes" the file
contents (well, it remembers how far it has got.) You can usually
rewind a file to the beginning, so:
I wonder if IO#each should be changed to automatically #rewind at the beginning of #each (if possible). I have difficulty imagining a situation where someone would purposely do
a = file.gets
file.each { ... }
But I can certainly imagine people iterating over a file multiple times. OTOH this may be too magical.
···
On Jun 6, 2006, at 9:42 PM, Mike Stok wrote:
On 6-Jun-06, at 9:36 PM, MB wrote:
In irb:
f = File.new('numbers.txt')
=> #<File:numbers.txt>
because as each iterates through the file it "consumes" the file contents (well, it remembers how far it has got.) You can usually rewind a file to the beginning, so:
I wonder if IO#each should be changed to automatically #rewind at the
beginning of #each (if possible). I have difficulty imagining a
situation where someone would purposely do
a = file.gets
file.each { ... }
But I can certainly imagine people iterating over a file multiple
times. OTOH this may be too magical.
Too magical. Streams are often one-way. If you need to read the same
data from the same stream more than once, usually the appropriate
method is to store the data in a variable to avoid that. Instead of:
f.each {|s| foo }
f.reset
f.each {|s| bar }
This may often work better:
data = f.read
data.each {|s| foo }
data.each {|s| bar }
because as each iterates through the file it "consumes" the file contents (well, it remembers how far it has got.) You can usually rewind a file to the beginning, so:
I wonder if IO#each should be changed to automatically #rewind at the beginning of #each (if possible). I have difficulty imagining a situation where someone would purposely do
a = file.gets
file.each { ... }
But I can certainly imagine people iterating over a file multiple times. OTOH this may be too magical.