So I'm not sure of the differences between the two approaches in Ruby but in C# we have the yield keyword (that can only be used when returning IEnumerable or IEnumerable (the generic Enumerable). What the yield keyword does is create a closure over the current environment creating an enumerator that uses that closure. It's easier to demonstrate in code than talk about it. Here is a Fibonnaci generator using yield:
public IEnumerable<long> Fibonnaci()
{
long current, previous;
if(current==0)
yield return current++;
(for byte i=2;i<128;i++) //Fibonacci numbers grow big quickly.
{
long tmp=current+previous;
previous=current;
current=tmp;
yield return tmp;
}
}
Note that I don't have to use recursion, I just evaluate my current value and return. Now if I want to get the xth Fibonnaci number I just create a function like so:
public long GetFibonacciNumber(byte count)
{
byte currentCount;
foreach(long value in Fibonacci())
{
if(++currentCount<count)
break;
return value;
}
}
Powerful stuff.