What is the general quick way to express the infinite enumerator `(1..Inf)` in Ruby?

I think the infinite enumerator is very convenient for writing FP style scripts, but I have yet to find a convenient way to build such a structure in Ruby.

I know that I can build it explicitly:

a = Enumerator.new do |y| i = 0 loop do y << i += 1 end end a.next #=> 1 a.next #=> 2 a.next #=> 3 ... 

but it is annoyingly verbose for such a simple structure.

Another approach is to β€œcrack” using Float::INFINITY :

 b = (1..Float::INFINITY).each b = (1..1.0/0.0).each 

These two are probably the least awkward solution I can give. Although I would like to know if there is any other more elegant way to build infinite counters. (By the way, why does Ruby just make inf or infinity as a literal for Float::INFINITY ?)

+5
source share
2 answers

Use # to_enum or # lazy to convert your Range to Enumerable . For instance:

 (1..Float::INFINITY).to_enum (1..Float::INFINITY).lazy 
+2
source

I would personally create my own Ruby class for this.

 class NaturalNumbers def self.each i = 0 loop { yield i += 1 } end end NaturalNumbers.each do |i| puts i end 
+1
source

Source: https://habr.com/ru/post/1207080/


All Articles