From: Bryan Weatherly Date: 2006-06-07T22:10:50+09:00 Subject: Re: What's going on here? (Newbie question) On Jun 6, 2006, at 11:43 PM, Logan Capaldo wrote: > > 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') >>> => # >>> >>> f.each {|line| puts line} >>> 123 >>> 456 >>> 789 >>> => # >>> >>> f.each {|line| puts line} >>> => # >>> >>> Why doesn't the second f.each work? >> >> 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: >> >> irb(main):001:0> f = File.new('numbers.txt') >> => # >> irb(main):002:0> f.each {|line| puts line} >> 123 >> 456 >> 789 >> => # >> irb(main):003:0> f.pos >> => 12 >> irb(main):004:0> f.each {|line| puts line} >> => # >> irb(main):005:0> f.pos >> => 12 >> irb(main):006:0> f.rewind >> => 0 >> irb(main):007:0> f.each {|line| puts line} >> 123 >> 456 >> 789 >> => # >> >> Note that some types of file can't be rewound. >> >> Take a look at what the pos method does, and see if this makes sense. >> >> Hope this helps, >> >> Mike >> >> -- >> >> Mike Stok >> http://www.stok.ca/~mike/ >> >> The "`Stok' disclaimers" apply. >> >> >> >> >> > > 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. > > What about using: f = IO.readlines(file) Then the entire file contents will be loaded line-by-line as an array. You wouldn't have to worry about rewinding the position in the actual file.