Ruby Language Enumerators Custom enumerators

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

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]


Got any Ruby Language Question?