StopIteration

StopIteration

StopIteration은 반복(iteration)을 멈추기 위해 던져지는 예외예요. 특히 Enumerator#next가 더 이상 다음 값을 줄 수 없을 때 이 예외를 던져요. IndexError를 상속받아요.

출처: Ruby 3.3 API

본문

Kernel#loop는 이 예외를 내부적으로 잡아서, 반복을 우아하게 끝내는 데 써요. loop 블록 안에서 StopIteration이 발생하면 루프를 빠져나가요.

loop do
  puts "Hello"
  raise StopIteration
  puts "World"
end
puts "Done!"

실행 결과는 이렇고요.

Hello
Done!

puts "World"StopIteration 때문에 실행되지 않은 거예요.

Public Instance Methods

result → value

반복자(iterator)의 반환값을 돌려줘요.

o = Object.new
def o.each
  yield 1
  yield 2
  yield 3
  100
end

e = o.to_enum

puts e.next                   #=> 1
puts e.next                   #=> 2
puts e.next                   #=> 3

begin
  e.next
rescue StopIteration => ex
  puts ex.result              #=> 100
end

each가 마지막으로 돌려준 값 100ex.result로 나오는 걸 볼 수 있어요.