Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the common fast way of expressing the infinite enumerator `(1..Inf)` in Ruby?

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

I know I can construct 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 that's annoyingly wordy for such a simple structure.

Another approach is sort of a "hack" of using Float::INFINITY:

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

These two are probably the least clumsy solution I can give. Although I'd like to know if there are some other more elegant way of constructing infinite enumerators. (By the way, why doesn't Ruby just make inf or infinity as a literal for Float::INFINITY?)

like image 408
xzhu Avatar asked Oct 20 '22 22:10

xzhu


1 Answers

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

(1..Float::INFINITY).to_enum
(1..Float::INFINITY).lazy
like image 136
Todd A. Jacobs Avatar answered Oct 22 '22 23:10

Todd A. Jacobs