Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading