You can read the file all at once:
content = File.readlines 'file.txt'
content.each_with_index{|line, i| puts "#{i+1}: #{line}"}
When the file is large, or may be large, it is usually better to process it line-by-line:
File.foreach( 'file.txt' ) do |line|
puts line
end
Sometimes you want access to the file handle though or control the reads yourself:
File.open( 'file.txt' ) do |f|
loop do
break if not line = f.gets
puts "#{f.lineno}: #{line}"
end
end
In case of binary files, you may specify a nil-separator and a block size, like so:
File.open('file.bin', 'rb') do |f|
loop do
break if not buf = f.gets(nil, 80)
puts buf.unpack('H*')
end
end
Finally you can do it without a block, for example when processing multiple files simultaneously. In that case the file must be explicitly closed (improved as per comment of @antinome):
begin
f = File.open 'file.txt'
while line = f.gets
puts line
end
ensure
f.close
end
References: File API and the IO API.