Is there a way to seek through a file without loading the whole thing into an array?

前端 未结 3 616
执念已碎
执念已碎 2021-01-05 15:54

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

3条回答
  •  青春惊慌失措
    2021-01-05 16:02

    Don't ignore the IO class. IO::foreach is one of those methods that returns an Enumerator, and can be lazily evaluated.

    IO#each_line is also another one that will return an Enumerator.

    In Ruby 2.0 we can call .lazy and use those methods, except for zip and cycle, that allow us to traverse the enumeration without bringing the whole file into memory.

提交回复
热议问题