Skip to content

Instantly share code, notes, and snippets.

@eugeneius
Last active November 7, 2016 22:23
Show Gist options
  • Save eugeneius/f280d683704129a5fd1ab0dbb8e54d84 to your computer and use it in GitHub Desktop.
Save eugeneius/f280d683704129a5fd1ab0dbb8e54d84 to your computer and use it in GitHub Desktop.
Demonstrating how Ruby's lazy enumerators and enum_for work.
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