On 28.10.2007 08:29, 7stud -- wrote:
> Konrad Meyer wrote:
>> Quoth 7stud --:
>>> #create a data file containing:
>>>
>>>     else
>>>       break
>>>     end
>>>
>>>   end
>>> end
>> IO#each_with_index and IO#readline are probably the same internally, so 
>> the
>> real answer here is that NO, IO#readline is NOT the same as
>> File.read.split('\n'), that's IO#readlines.
>>
> 
> The real question is: does readline do any buffering?  What about 
> each()?  If a file has ten lines in it, does ruby access the file ten 
> times?  Or, does ruby read some reasonable amount of data into a buffer?

Ruby does buffering but will not read the whole file unless asked to do so.

There are several ways to access only lines 4 through 7.  For example:

# 1
require 'enumerator' # pre 1.9
File.to_enum(:foreach, "foo.dat").each_with_index do |line,idx|
   case idx
     when 0...3
       # ignore
     when 3...7
       puts line
     else
       break # or return or exit
   end
end


# 2
File.open("foo.dat") do |io|
   io.each do |line|
     case io.lineno
       when 1...4
         # ignore
       when 4..7
         puts line
       else
         break
     end
   end
end

# 3
File.foreach "foo.dat" do |line|
   case $.
     when 1...4
       # ignore
     when 4..7
       puts line
     else
       break
   end
end

Kind regards

	robert