Created
July 10, 2018 16:58
-
-
Save aemadrid/460c5cc5a825a7d382c86a2cf01ce09e to your computer and use it in GitHub Desktop.
Efficiently reading files in Ruby. From https://blog.appsignal.com/2018/07/10/ruby-magic-slurping-and-streaming-files.html
This file contains hidden or 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 MyIO | |
def initialize(filename) | |
fd = IO.sysopen(filename) | |
@io = IO.new(fd) | |
@buffer = "" | |
end | |
def each(&block) | |
@buffer << @io.sysread(512) until @buffer.include?($/) | |
line, @buffer = @buffer.split($/, 2) | |
block.call(line) | |
each(&block) | |
rescue EOFError | |
@io.close | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment