I recently start to read the book "Programming Ruby 1.9&2.0". It shows a trick for explicit enumerator
triangular_numbers = Enumerator.new do |yielder|
number = 0
count = 1
loop do
number += count
count += 1
yielder.yield number
end
end
5.times { print triangular_numbers.next, " " }
puts
I wonder why this yielder.yield will leave the loop temporarily and also return the value of number until the next enumerator object created. It seems different than the usual case when a yield inside the loop block. I check the APIdock and find that the source code of Proc.yield() is the same as Proc.call(). For the Yielder object in the Enumerator class, the Yielder has override the yield(). But why the yielder.yield will temporarily leave the loop block?
Reference: APIdock Yielder yield(), Ruby MRI rb_proc_call