Selective file read in Ruby

I have a huge file that looks like this:

7

bla1
blala
blabla
blab
blals
blable
bla

more here..

The first numbers indicate how many values ​​I will have. The fact is that I just want to point directly to line 11 (the text "more details here .."), without having to read all these values ​​earlier. In my case, I have a large number of numbers, so it needs to be optimized.

Would you recommend something to me?

+3
source share
4 answers

You can do something like a file that will skip the first N lines:

SkipFile.open("/tmp/frarees") do |ln|
  puts ln                                   # "more here.." and so on
end

puts SkipFile.new("/tmp/frarees").readline  # "more here.."

Same:

class SkipFile
  def self.open(fn, &block)
    sf = SkipFile.new(fn)
    return sf unless block
    sf.each(&block)
  end

  def initialize(fn)
    @f = File.open(fn)
    skip = @f.readline.to_i     # Skip N lines as prescribed by the file
    skip.times { @f.readline }  # this could be done lazily
  end

  def each(&block)
    @f.each(&block)
  end

  def readline
    @f.readline
  end
end

, . , File IO ( . Delegate), .

+3

, File # seek .

, , . , , .

+5

, , , .

File.readlines(file_path)[10..-1] # indexing starts from 0
+1

, , , , , "".

f = File.open('./data')
(f.readline.to_i + 2).times { f.readline }
p f.readline
+1

All Articles