Skip to content

Instantly share code, notes, and snippets.

@no-reply no-reply/infinite_enum.rb
Last active Jan 29, 2016

Embed
What would you like to do?
my_enum = (1..5).lazy.map { |i| i == 3 ? raise(StandardError) : i }
safe_enum = Enumerator.new do |y|
loop do
begin
y.yield my_enum.next
rescue => e
break if e.kind_of? StopIteration
end
end
end
safe_enum.take(100) # => [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
# https://www.destroyallsoftware.com/talks/wat
@rthbound

This comment has been minimized.

Copy link

commented Jan 29, 2016

my_enum = (1..5).lazy.map { |i| i == 3 ? raise(StandardError) : i }

safe_enum = Enumerator.new do |y|
  loop do
    begin
      y.yield my_enum.next
    rescue StopIteration
      break
    rescue
      y.yield my_enum.feed(nil)
    end
  end
end

safe_enum.take(100) #=> [1, 2, nil, 1, 2, nil, 1, 2, nil, 1, 2, ...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.