Created
February 14, 2012 15:46
-
-
Save mks-m/1827669 to your computer and use it in GitHub Desktop.
File.each_lines_batch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IO | |
def each_lines_batch(batch_size=1000, buffer_size=4096) | |
lines = [] | |
chunk = "" | |
while data = file.read(buffer_size) | |
chunk << data | |
lines += chunk.lines.to_a | |
# last line might not be read until it's end | |
chunk = lines.pop | |
while lines.size > batch_size | |
batch = lines.shift(batch_size) | |
yield batch | |
end | |
end | |
lines += chunk.lines.to_a | |
yield lines if lines.any? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment