Consider a simple Enumerator like this:
natural_numbers = Enumerator.new do |yielder|
number = 1
loop do
yielder.yield number
number += 1
end
end
My question is: Why does ruby require that we invoke yield on the yielder object? Said another way: Why can’t we replace yielder.yield number with yield number? In this example, it would be appear to be the same thing, if it were allowed. Are there examples where yielder is used in a nontrivial way? If so, can you give one? If not, what is the purpose of yielder?
Thanks.
Not 100% sure if that’s the reason, but
yieldalone (always) applies to the block submitted to the method which callsyield: in your case the method which containsnatural_numbersassignment; and it’s not possible for it to perform what is desired forEnumerator, i.e. to emit the Enumerator element. Although bearing the same name,Yielder#yieldis a method, and Ruby’syieldis a statement.In other words, it would not be possible to implement
Enumeratorconstructor which would work withyieldstatement.