Ruby Language Custom enumerators


Example

Let's create an Enumerator for Fibonacci numbers.

fibonacci = Enumerator.new do |yielder|
  a = b = 1
  loop do
    yielder << a
    a, b = b, a + b
  end
end

We can now use any Enumerable method with fibonacci:

fibonacci.take 10
# => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]