Last active
November 7, 2016 22:23
-
-
Save eugeneius/f280d683704129a5fd1ab0dbb8e54d84 to your computer and use it in GitHub Desktop.
Demonstrating how Ruby's lazy enumerators and enum_for work.
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
def each_char_matching_pattern(io, pattern) | |
return enum_for(:each_char_matching_pattern, io, pattern) unless block_given? | |
io.each_line.lazy.select do |line| | |
line =~ pattern | |
end.flat_map do |line| | |
line.chars | |
end.each do |line| | |
yield line | |
puts "\toffset: #{io.pos}" | |
end | |
end | |
lazy_stream = each_char_matching_pattern(DATA, /foo/) | |
lazy_stream.each do |char| | |
print char | |
end | |
__END__ | |
foo bar | |
baz | |
bux | |
bar foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment