rubygeneratorenumerator

Ruby enumerator not returning next value


I'm trying to create a generator in Ruby that always returns the next value. For example

def all_numbers
  Enumerator.new do |yielder|
    number = 0
    count = 1
    loop do
      number += count
      count += 1
      yielder.yield number
    end
  end
end

I expect the above code to return

all_numbers.next # 1
all_numbers.next # 2
all_numbers.next # 3
# etc

However, I keep just keeping 1 over and over again.

What am I missing?


Solution

  • Your method returns a new Enumerator every time you call it. So, you never ask for the second element. You create a new Enumerator, ask for its first element, throw the Enumerator away, create a new one, ask for its first element, throw it away, etc.

    You need to actually store the Enumerator somewhere and call its next method multiple times:

    enum = all_numbers
    
    enum.next #=>   1
    enum.next #=>   3
    enum.next #=>   6
    enum.next #=>  10
    enum.next #=>  15
    enum.next #=>  21
    enum.next #=>  28
    enum.next #=>  36
    enum.next #=>  45
    enum.next #=>  55
    enum.next #=>  66
    enum.next #=>  78
    enum.next #=>  91
    enum.next #=> 105
    enum.next #=> 120