This works:
f = File.new(\"myfile\").readlines
f[0] #=> \"line 1\"
f[21] #=> \"line 22\"
But what if I have a very large file, and on
For the purpose you can use the each_line
iterator, combined with with_index
to have the line number of the current line (counting from 0):
File.open('myfile') do |file|
file.each_line.with_index do |line, lineno|
case lineno
when 0
# line 1
when 21
# line 22
end
end
end
By using open
, passing a block to it, instead of new
, you are guaranteed that the file is properly closed at the end of the block execution.
Update The with_index
method accepts an optional argument to specify the starting index to use, so che code above could be better written like this:
file.each_line.with_index(1) do |line, lineno|
case lineno
when 1
# line 1
end
end