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?
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
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]