Understanding and Using Iterators - Perl.com

sub gen_fib {
    my ($low, $high) = (1, 0);

    return sub {
        ($low, $high) = ($high, $low + $high);
        return $high;
    };
}

my $fib = gen_fib();
print $fib->(), "\n" for 1 .. 20;

Besides the funny initialization of $low being greater than $high, it also misses 0, which should be the first item returned. Here is one way to handle it:

sub gen_fib {

    my ($low, $high) = (1, 0);

    my $seen_edge;

    return sub {
        return 0 if ! $seen_edge++;
        ($low, $high) = ($high, $low + $high);
        return $high;
    };
}

State Variables Persist As Long As the Iterator

在古早的 Perl 中,iterator (customized iterator / generator) 可以用 closure 機制來實作。

需要 generator 的情況:用少一點記憶體、無窮元素、循環、太大。文中對每個情況都給一個例子。

ruby - Meaning of the word yield - Stack Overflow

The word yield doesn't really have any special meaning in the context of Ruby. It means the same thing as it means in every other programming language, or in programming and computer science in general.

It is usually used when some kind of execution context surrenders control flow to a different execution context. For example, in Unix, there is a sched_yield function which a thread can use to give up the CPU to another thread (or process). With coroutines, the term yield is generally used to transfer control from one coroutine to another. In C#, there is a yield keyword, which is used by an iterator method to give up control to the iterating method.

And in fact, this last usage is exactly identical to the usage of the Enumerator::Yielder#yield method in Ruby, which you were asking about. Calling this method will suspend the enumerator and give up control to the enumerating method.

Example:

...

As you see, there is an infinite loop. Obviously, if this loop just ran on its own, it wouldn't be of much use. But since every time it hits the yield method, it gives up control until it is called again, this will produce the Fibonacci numbers one by one, essentially representing an infinitely long list of all Fibonacci numbers.

There is another method, Fiber.yield, which serves a similar purpose. (In fact, I already described it above, because Fiber is just Ruby's name for coroutines.) Inside a Fiber, you call Fiber.yield to give up control back to the execution context that originally gave control to you.

Lastly, there is the yield keyword, which is used inside a method body to give up control to the block that was passed into the method.

Note that, at least in the Enumerator case (i.e. the first example), you can additionally interpret yield as to produce, since the Enumerator produces a new value, every time it calls yield.

解釋 yield 這個字的意思,以及在 ruby 中的 Fiber#yield 與 關鍵字yield 的差別:

Fiber#yield →將「控制權」還給之前「放控制權給你的fiber」。
yield→將「控制權」交給「傳入的block」。(也就是 callback)