Ruby provides a yield statement that eases the creation of iterators.
The first thing I noticed was that its behavior is different from the C# yield statement (which I knew from before).
Ruby's yield statement gives control to a user specified block from the method's body. A classic example is the Fibonacci Sequence:
class NumericSequences
def fibo(limit)
i = 1
yield 1
yield 1
a = 1
b = 1
while (i < limit)
t = a
a = a + b
b = t
yield a
i = i+1
end
end
...
end
The fibo method can be used by specifying a block that will be executed each time the control reaches a yield statement. For example:
irb(main):001:0> g = NumericSequences::new
=> #<NumericSequences:0xb7cd703c>
irb(main):002:0> g.fibo(10) {|x| print "Fibonacci number: #{x}\n"}
Fibonacci number: 1
Fibonacci number: 1
Fibonacci number: 2
Fibonacci number: 3
Fibonacci number: 5
Fibonacci number: 8
Fibonacci number: 13
Fibonacci number: 21
Fibonacci number: 34
Fibonacci number: 55
Fibonacci number: 89