0

In Python, we can write something like this to generate all positive integers:

def integer():
  count = 0
  while True:
    count += 1
    yield count

Is there a way to write a similar generator in Ruby?

Andy
  • 49,085
  • 60
  • 166
  • 233
Cisplatin
  • 2,860
  • 3
  • 36
  • 56

2 Answers2

2

It's very similar:

def integer
  Enumerator.new do |y|
    n = 0
    loop do
      y << n
      n += 1
    end
  end
end

That can be used like this:

integer.take(20).inject(&:+)
# => 190
tadman
  • 208,517
  • 23
  • 234
  • 262
1

You want a lazy enumerator. In Ruby 2.3.1 (and at least as far back as Ruby 2.2.0), you can make one yourself by mixing in Enumerator::Lazy.

However, if all you want is an infinite stream of integers, you could just use a Range object. For example:

(1 .. Float::INFINITY).take 10
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199