Search code examples
rubyyieldenumerator

Why does Enumerator.new require a "yielder" object?


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.


Solution

  • Not 100% sure if that's the reason, but yield alone (always) applies to the block submitted to the method which calls yield: in your case the method which contains natural_numbers assignment; and it's not possible for it to perform what is desired for Enumerator, i.e. to emit the Enumerator element. Although bearing the same name, Yielder#yield is a method, and Ruby's yield is a statement.

    In other words, it would not be possible to implement Enumerator constructor which would work with yield statement.