4

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.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Eman
  • 43
  • 3

2 Answers2

6

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.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Johannes Müller
  • 5,581
  • 1
  • 11
  • 25
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
WPeN2Ic850EU
  • 995
  • 4
  • 8