Search code examples
crystal-lang

What is the proper way to check if an Iterator is complete?


As the title states, I'd like to know the proper way to check if an iterator is complete.

I couldn't find anything in the docs but I found something like this in the source:

iter.next.is_a? Iterator::Stop

Toy example:

a = "a世c"
b = a.each_char

puts b.next # a
puts b.next # 世
puts b.next # c
puts b.next # #<Iterator::Stop:0x8ccbff8>

if b.next.is_a? Iterator::Stop
  puts "DONE" # successfully prints DONE
end

Is this correct and proper or is there a different way I should use.


Solution

  • Yes, that's the proper way. But most of the time you don't need to deal with next, you just chain iterators and get a result out of them.