'Crystal get from n line to n line from a file

How can I get specific lines in a file and add it to array?

For example: I want to get lines 200-300 and put them inside an array. And while at that count the total line in the file. The file can be quite big.



Solution 1:[1]

File.each_line is a good reference for this:

lines = [] of String
index = 0
range = 200..300

File.each_line(file, chomp: true) do |line|
  index += 1
  if range.includes?(index) 
    lines << line
  end
end

Now lines holds the lines in range and index is the number of total lines in the file.

Solution 2:[2]

To prevent reading the entire file and allocating a new array for all of its content, you can use File.each_line iterator:

lines = [] of String

File.each_line(file, chomp: true).with_index(1) do |line, idx|
  case idx
  when 1...200  then next          # ommit lines before line 200 (note exclusive range)
  when 200..300 then lines << line # collect lines 200-300
  else break                       # early break, to be efficient
  end
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rogerdpack
Solution 2