Skip to content

Instantly share code, notes, and snippets.

@no-reply
Last active January 29, 2016 16:58
Show Gist options
  • Save no-reply/4b38f26b3fe32ad266a7 to your computer and use it in GitHub Desktop.
Save no-reply/4b38f26b3fe32ad266a7 to your computer and use it in GitHub Desktop.
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
Copy link

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