On 6-Jun-06, at 9:36 PM, MB wrote:

> In irb:
>
> f = File.new('numbers.txt')
> => #<File:numbers.txt>
>
> f.each {|line| puts line}
> 123
> 456
> 789
> => #<File:numbers.txt>
>
> f.each {|line| puts line}
> => #<File:numbers.txt>
>
> 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')
=> #<File:numbers.txt>
irb(main):002:0> f.each {|line| puts line}
123
456
789
=> #<File:numbers.txt>
irb(main):003:0> f.pos
=> 12
irb(main):004:0>  f.each {|line| puts line}
=> #<File:numbers.txt>
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
=> #<File:numbers.txt>

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 <mike / stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.